2014-04-16 43 views
-2
var array1 = ["hello", "sam", "how"]; 

var emptyArray2 = []; 

array1.join(" "); 

我需要取出array1中每个元素的第一个字母和最后一个字母,并将其推送到emptyArray2。将其转换为字符串后,我不知道该做什么。我想我需要使用for循环来通过它,然后我将如何提取每个元素中的第一个和最后一个字母并将其推送到emptyArray2?取出数组中的每个元素的第一个字母和最后一个字母(javascript)

+0

以一个字母在字符串可以做使用'str [i]'。至于推入数组,搜索“推数组javascript”。 –

+0

@dystroy我只需要第一个和最后一个。怎么会把剩下的放在外面? – user3525853

+0

@ user3525853预期输出是什么? – thefourtheye

回答

0
var array1 = ["hello", "sam", "how"], result = []; 
array1.forEach(function(currentString) { 
    result.push(currentString.charAt(0)); // First character 
    result.push(currentString.charAt(currentString.length - 1)); //Last character 
}); 
console.log(result); 
# [ 'h', 'o', 's', 'm', 'h', 'w' ] 
+0

你应该使用'.charAt()'而不是字符串索引。 – jfriend00

+1

@ jfriend00当然,但你能告诉我为什么吗? – thefourtheye

+0

@thefourtheye,请参阅['string.charAt(x)or string [x]?'](http://stackoverflow.com/questions/5943726/string-charatx-or-stringx)基本上,IE7不支持字符串索引。 –

2

遍历数组并返回字符串减去第一个字符和最后一个字符。 地图功能将创建一个新的数组,子串需要索引1的所有字符的字符串的总长度 - 1.

var array2 = ["hello", "sam", "how"].map(function(p){return p.substring(1, p.length - 1)}) 
+1

这不会删除每个元素中的第一个和最后一个字母。 – jfriend00

+0

我的不好,认为只有第一个字符应该被删除,我更新了子字符串。 – Hatsjoem

0
var array1 = ["hello", "sam", "how"]; 

var emptyArray2 = []; 

array1.forEach(function(item){ 
//item.charAt(0) will give character at start of string 
//item.charAt(item.length-1) will give character at end of string 
emptyArray2.push(item.charAt(0),item.charAt(item.length-1)); 
//Array.push(..) is to append elements into the array 
}); 
console.log(emptyArray2); // will print ["h","o","s","m","h","w"] in console 
相关问题