合并数组元素的技巧有很多,这里列举一些常见的方法:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArr = [];
for (let i = 0; i < arr1.length; i++) {
mergedArr.push(arr1[i]);
}
for (let i = 0; i < arr2.length; i++) {
mergedArr.push(arr2[i]);
}
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArr = arr1.concat(arr2);
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArr = [...arr1, ...arr2];
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArr = arr1.slice(); // 创建arr1的副本,避免修改原数组
Array.prototype.push.apply(mergedArr, arr2);
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArr = arr1.slice(); // 创建arr1的副本,避免修改原数组
mergedArr.splice(mergedArr.length, 0, ...arr2);
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
根据你的需求和编程语言,可以选择合适的方法来合并数组元素。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。