Jquery,查找包含一个值的子数组
Jquery, Find a subarray that contains a value
我想将一个变量“推入”一个包含值的子数组。这是为了整合成一个“for循环”。但它不起作用..:-(我的错误在哪里?谢谢。
var add = "purple";
var val = "white";
arr = [
["blue","green","brown"],
["white","gray","black"],
["yellow","pink","red"]
];
subarr = [].indexOf(val) > -1;
arr[subarr].push(add);
/*
expected output :
arr = [
["blue","green","brown"],
["white","gray","black","purple"],
["yellow","pink","red"]
]
*/
您正在寻找
subarr = [].indexOf(val) > -1;
进入一个空数组。
相反,您可以找到子数组,如果存在则将值推送给它。
const
add = "purple";
val = "white",
arr = [["blue", "green", "brown"], ["white", "gray", "black"], ["yellow", "pink", "red"]],
sub = arr.find(a => a.includes(val));
if (sub) sub.push(add);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我想将一个变量“推入”一个包含值的子数组。这是为了整合成一个“for循环”。但它不起作用..:-(我的错误在哪里?谢谢。
var add = "purple";
var val = "white";
arr = [
["blue","green","brown"],
["white","gray","black"],
["yellow","pink","red"]
];
subarr = [].indexOf(val) > -1;
arr[subarr].push(add);
/*
expected output :
arr = [
["blue","green","brown"],
["white","gray","black","purple"],
["yellow","pink","red"]
]
*/
您正在寻找
subarr = [].indexOf(val) > -1;
进入一个空数组。
相反,您可以找到子数组,如果存在则将值推送给它。
const
add = "purple";
val = "white",
arr = [["blue", "green", "brown"], ["white", "gray", "black"], ["yellow", "pink", "red"]],
sub = arr.find(a => a.includes(val));
if (sub) sub.push(add);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }