[英]How do I remove the first letter of every string in array with splice?
I have an array that contains multiple strings. 我有一个包含多个字符串的数组。 I need to store each string minus the first letter and then concatenate them into a sentence.
我需要存储每个字符串减去第一个字母,然后将它们连接成一个句子。
I am trying: 我在尝试:
var missingFirstLetter = array[i].splice(1);
What I have found online guides me to believe this should work, but it doesn't work as intended. 我在网上找到的东西引导我相信这应该有用,但它不能按预期工作。
You should slice (not splice!) each element of the array and then store it back into an array , which you can do with Array#map
, which maps each element to a new value, in this case the string without the first letter: 你应该切片(不拼接!)数组的每个元素,然后将它存储回一个数组 ,你可以使用
Array#map
,它将每个元素映射到一个新值,在这种情况下是没有第一个字母的字符串:
var arrayNoFirstLetter = array.map(el => el.slice(1));
This will iterate through the array and map each element to a new string without the first letter and store the new array of strings into arrayNoFirstLetter
. 这将迭代数组并将每个元素映射到没有第一个字母的新字符串,并将新的字符串数组存储到
arrayNoFirstLetter
。 Make sure to use String#slice
to get a section of a string, because there is not String#splice
method. 确保使用
String#slice
来获取字符串的一部分,因为没有String#splice
方法。 (maybe you mistook it for Array#splice
?) Then you can use Array#join
to join them with a delimiter (which is the string between each element when joined together): (也许你把它误认为是
Array#splice
?)然后你可以使用Array#join
将它们与一个分隔符连接起来(这是连接在一起时每个元素之间的字符串):
var joined = arrayNoFirstLetter.join(""); //join with empty space for example
For example: 例如:
var array = ["Apples", "Oranges", "Pears"];
var arrayNoFirstLetter = array.map(el => el.slice(1)); // ["pples", "ranges", "ears"]
var joined = arrayNoFirstLetter.join(""); // "pplesrangesears"
Is it what you wanted? 这是你想要的吗?
var strings = ['string1', 'string2', 'string3'],
stringsNoFirstCh = [];
for(key in strings){ // Iterates through each string in an array
let string = strings[key];
var s = string.substring(1); // Gets a string starting from index 1, so omits the first char
stringsNoFirstCh.push(s); // Add to a new array: ['tring1', 'tring2', 'tring3']
}
var string = stringsNoFirstCh.join(''); // Transform to a string: tring1tring2tring3
Try this: 试试这个:
var a=["hHello","+-I-am","d-evil"];
var x;
var z="";
for(var i=0;i<a.length;i++){
x=a[i].substring(1);
z=z+x;
}
console.log(z);
Result is : 结果是:
Hello-I-am-evil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.