取出数组中每个元素的第一个和最后一个字母(javascript)

时间:2014-04-16 07:46:29

标签: javascript arrays

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

var emptyArray2 = [];

array1.join(" ");

我需要取出array1中每个元素的第一个字母和最后一个字母,并将其推送到emptyArray2。将它转换为字符串后我不知道该怎么做。我想我需要使用for循环来完成它,然后我将如何拉出每个元素中的第一个和最后一个字母并推送到emptyArray2?

4 个答案:

答案 0 :(得分:2)

循环遍历数组并返回字符串减去第一个char和最后一个char。 map函数将创建一个新数组,substring将索引1的所有字符转换为字符串的总长度 - 1.

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

答案 1 :(得分: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' ]

答案 2 :(得分: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

答案 3 :(得分:0)

执行此操作的更多方法:

// Create a new array
let array = [ "hello", "sam", "how" ];


// Finding the first letters from the array items.
let firstLetters1 = array.map(eachItemInArray => {
    return eachItemInArray[0];
})

// Display the result
console.log("First letters of items in the array are: ");
console.log(firstLetters1);

// Another short cut way of writing the above code in a single line.
let firstLetters2 = array.map(eachItemInArray => eachItemInArray[0]);

// Display the result
console.log("First letters of items in the array are (short cut method): ");
console.log(firstLetters2);


// Finding the last letters from the array items.
let lastLetters1 = array.map(eachItemInArray => {
    let index = eachItemInArray.length - 1;
    return eachItemInArray[index];
})

// Display the result
console.log("Last letters of items in the array are: ");
console.log(lastLetters1);

// Another short cut way of writing the above code in a single line
let lastLetters2 = array.map(eachItemInArray => eachItemInArray[eachItemInArray.length - 1]);

// Display the result
console.log("Last letters of items in the array are (short cut method): ");
console.log(lastLetters2);

我已经展示了使用地图的长途旅行和使用JavaScript的单行方式。