遍历一个数组,并根据条件将值添加到第二个数组

时间:2019-06-14 12:21:16

标签: javascript arrays loops

我必须将值从一个数组传递到另一个数组,条件是名称以“ A”开头。

var favorites = []
var famous = [
  'alex smith', 'amy whinehouse', 
  'cameron diaz', 'brad pitt', 
  'ashton kutcher', 'mark whalberg', 
  'morgan freeman', 'mila kunis']
for (var i=0; i<famous.length; i++ ) { 
  if(famous[i][0]==="a") {
    favorites.push((famous[i][0]).unshift()) 
  }
}

控制台向我返回错误。

2 个答案:

答案 0 :(得分:0)

使用ES6,您可以这样编写:

var famous = ['alex smith', 'amy whinehouse', 'cameron diaz', 'brad pitt', 'ashton kutcher', 'mark whalberg', 'morgan freeman', 'mila kunis']
var favorites = famous.filter(artist => artist[0] == 'a');
 
console.log(favorites)

您的原始代码应如下所示:

var favorites = []
var famous = ['alex smith', 'amy whinehouse', 'cameron diaz', 'brad pitt', 'ashton kutcher', 'mark whalberg', 'morgan freeman', 'mila kunis']
for (var i=0; i<famous.length; i++) { 
    if (famous[i][0]==='a') {
        favorites.push(famous[i]); 
    }
}
console.log(favorites)

您的错误代码TypeError: famous[i][0].unshift is not a function表示您试图在非数组对象上使用数组函数。您是在字符串上调用函数unshift,但对于根本不存在该函数的字符串。

答案 1 :(得分:0)

您可以使用过滤器方法

var favorites = [];
var famous = [
  'alex smith', 'amy whinehouse', 
  'cameron diaz', 'brad pitt', 
  'ashton kutcher', 'mark whalberg', 
  'morgan freeman', 'mila kunis'];
  
var favorites = famous.filter((artist, index) => {
  if (artist[0] == 'a') {
    delete famous[index];
    return true
  }
  return false;
});  
famous = famous.filter(Boolean)

console.log(famous)
console.log(favorites)