为什么我在尝试映射 2D 数组时得到 "u" 的输出?



我试图使玉米也有"果汁"在它的末尾,我正在试验一个二维数组。如果我取出数组并使其为1d,那么我就能够在每个水果的末尾得到"果汁"。异常的是玉米,我无法显示"玉米汁"。实际上,下面的输出给了我"u"。"

为什么我用下面的代码得到"u"的输出,以及我如何使用映射方法在2d数组中返回"玉米汁"?

fruits = ["corn"["apple","orange","grape"]];
var fruitJuice = fruits.map(function (fruit){
return fruit + " juice";
});
fruitJuice[0][0];
fruits = ["corn"["apple","orange","grape"]];

不太有意义。这样做

fruits = ["corn","apple","orange","grape"]; // a normal linear array

除非你是认真的?

fruits = ["corn",["apple","orange","grape"]]; //an array  with  a string and array (2d)

还是这个?

fruits = {"corn":["apple","orange","grape"]}; //an object where corn represents the array

更新:访问所有级别并添加'果汁',虽然在这种情况下要做的事情有点奇怪,但我会这样做-使用地图对此将毫无帮助

fruits = ["corn",["apple","orange","grape"]];
juices = [];
for (var i in fruits){
     if(fruits[i].constructor === Array){
        for (var x in fruits[i]){
              juices.push(fruits[i][x] + " juice");
        }
     }else{
        juices.push(fruits[i] + " juice");
     }
}
alert(juices);
//juices

这里假设元素可以是数组或字符串....

相关内容

  • 没有找到相关文章

最新更新