Javascript 如何从另一个数组中获取相同的值并分配给数组对象
在本文中,我们将学习如何从另一个数组中获取相同的值并将其分配给数组对象。要从另一个数组中获取相同的值并将其插入到数组对象中,我们需要:
- 比较两个数组的每个元素
- 返回匹配的元素
- 将元素或对象添加到数组对象中
我们可以使用以下方法来实现:
- 使用 forEach() 和 push()
- 使用 filter() 和 push()
方法1:使用 forEach() 和 push()
在此方法中,我们将使用数组的 forEach()、push()和includes()方法来从另一个数组中获取相同的值,并将其分配给数组对象。
示例:
// Define first array
let arr1 = [1, 2, 3, 4, 5,
77, 876, 453];
// Define second array
let arr2 = [1, 2, 45, 4, 231, 453];
// Create a empty object of array
let result = [];
// Checked the matched element between two
// array and add into result array
arr1.forEach(val =>
arr2.includes(val) && result.push(val));
// Print the result on console
console.log(result);
输出
[ 1, 2, 4, 453 ]
方法2: 使用 filter() 和 push()
在这种方法中,我们将使用数组的filter()、push()和includes()来从另一个数组中获取相同的值,并将其赋值给数组对象。
示例:
// Define first array
let arr1 = [1, 2, 3, 4, 5,
77, 876, 453];
// Define second array
let arr2 = [1, 2, 45, 4, 231, 453];
// Checked the matched element between two array
// and add into the result array
let result = arr1.filter(
val => arr2.includes(val));
// Print the result on console
console.log(result);
输出
[ 1, 2, 4, 453 ]
极客教程