【问题标题】:JS - populate an array from another array + modify valuesJS - 从另一个数组填充一个数组+修改值
【发布时间】:2013-02-08 23:56:52
【问题描述】:

有人可以帮我用 JavaScript 做以下事情吗:

  • 我有一个包含字符串的数组 (array1)
  • 我需要遍历初始数组 (array1) 的每个元素
  • 那么我需要获取array1中每个索引的值,并为每个值添加一个字母
  • 最后将array1中每个索引的修改值写入array2。

谢谢。

【问题讨论】:

标签: javascript arrays


【解决方案1】:
//declares the array and initializes it with strings
var array1 = ["one", "two", "three", "four"];

//declares the second array
var array2 = []; 

//this line begins the loop. Everything inside the { } will run once for every single item inside array1
for (var i = 0; i < array1.length; i++) 
{
    //this gets the contents of the array at each interval
    var string = array1[i]; 

    //here we take the original string from the array1 and add a letter to it.
    var combo = string + "A"; 

    //this line takes the new string and puts it into the 2nd array
    array2.push(combo); 
}

//displays a message box that shows the contents of the 2nd array
alert(array2); 

【讨论】:

    【解决方案2】:

    使用 Array.map 的示例。

    var singularArray = ['Dog', 'Cat', 'Bird'],
    pluralArray = singularArray.map(function(value){
        return value+'s';
    });
    
    console.log(pluralArray); //Logs ['Dogs', 'Cats', 'Birds']
    

    http://jsfiddle.net/fzakf/

    详情请见https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多