使用 javascript/ 节点 js 将 5 个字符串从数组推送到新的新数组

push 5 string from array to new new Array using javascript/ node js

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];

for (const value of dataArray){
 let newArray=[];
 for(i=0;i<5;i++)
 {
  newArray.push(value);
 }
 
 console.log(newArray)
}

我试图从数组中仅推送 5 个字符串,但它没有按预期工作,因为我的预期输出是这样的

console.log(newArray);

["A1","A2","A3","A4","A5"]

我正在尝试从 dataArray 中获取前 5 个字符串并将它们推送到 newArray

slice 方法将为您完成这项工作。

例如:dataArray.slice(0, 5); - 这将 return 来自 dataArray 的前 5 个项目。

在您的代码中,您正在遍历 dataArray 并将 dataArray 中的每个项目推入 newArray 5 次并打印它。 同样在通过 dataArray 的每次迭代中,变量 newArray 被重新初始化。

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];


 let newArray=[];
 for(i=0;i<5;i++)
 {
  newArray.push(dataArray[i]);
 }
 
 
console.log(newArray);

另一种方式是.slice()

所以你可以做到这一点

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];

 console.log(dataArray.slice(0,5))

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];
let newArr = dataArray.filter((str,index) => {
    if(index < 5){
  return str;
  }
})
console.log(newArr)