var array1 = ["hello", "sam", "how"];
var emptyArray2 = [];
array1.join(" ");
我需要取出array1中每个元素的第一个字母和最后一个字母,并将其推送到emptyArray2。将其转换为字符串后,我不知道该做什么。我想我需要使用for循环来通过它,然后我将如何提取每个元素中的第一个和最后一个字母并将其推送到emptyArray2?取出数组中的每个元素的第一个字母和最后一个字母(javascript)
var array1 = ["hello", "sam", "how"];
var emptyArray2 = [];
array1.join(" ");
我需要取出array1中每个元素的第一个字母和最后一个字母,并将其推送到emptyArray2。将其转换为字符串后,我不知道该做什么。我想我需要使用for循环来通过它,然后我将如何提取每个元素中的第一个和最后一个字母并将其推送到emptyArray2?取出数组中的每个元素的第一个字母和最后一个字母(javascript)
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' ]
你应该使用'.charAt()'而不是字符串索引。 – jfriend00
@ jfriend00当然,但你能告诉我为什么吗? – thefourtheye
@thefourtheye,请参阅['string.charAt(x)or string [x]?'](http://stackoverflow.com/questions/5943726/string-charatx-or-stringx)基本上,IE7不支持字符串索引。 –
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
以一个字母在字符串可以做使用'str [i]'。至于推入数组,搜索“推数组javascript”。 –
@dystroy我只需要第一个和最后一个。怎么会把剩下的放在外面? – user3525853
@ user3525853预期输出是什么? – thefourtheye