我正在尝试从Javascript中的每个数组元素中提取第一个字符,所以我最终提取了1,4,7,2,5和8,但我一直得到“extractElement is不是一个功能“我做错了什么?
var characterArray = ['123','456','789','234','567','890'];
var extractElement;
var extractSlicedCharacter;
function extractEachFirstNumber(){
for(counter = 0; counter <= characterArray.length; counter++){
extractElement = characterArray[counter];
extractSlicedCharacter = extractElement.slice(0,1);
}
}
答案 0 :(得分:0)
除了你应该将循环逻辑从<=
更改为<
var characterArray = ['123','456','789','234','567','890'];
var extractElement;
var extractSlicedCharacter;
function extractEachFirstNumber(){
for(counter = 0; counter < characterArray.length; counter++){
extractElement = characterArray[counter];
extractSlicedCharacter = extractElement.slice(0,1);
console.log(extractSlicedCharacter);
}
}
extractEachFirstNumber();
答案 1 :(得分:0)
@depperm答案应解决问题
另一种方式可能是
var outputArray = [];
characterArray.forEach( function(element){
outputArray.push( element.charAt(0) );
} );
console.log( outputArray );
答案 2 :(得分:0)
Slice返回一个数组,而不是单个字符。你应该使用charAt。
var characterArray = ['123','456','789','234','567','890'];
var extractElement;
var extractSlicedCharacter;
function extractEachFirstNumber(){
for(counter = 0; counter <= characterArray.length; counter++){
extractElement = characterArray[counter];
alert(extractElement.charAt(1));
//extractSlicedCharacter = extractElement.charAt(1);
}
}
答案 3 :(得分:0)
您也可以通过方便地使用Array#map方法执行以下操作:
result = characterArray.map(function(el) {return el[0]})
//=> [ '1', '4', '7', '2', '5', '8' ]