在Javascript中切片数组的每个字符串值元素 [英] Slice each string-valued element of an array in Javascript
本文介绍了在Javascript中切片数组的每个字符串值元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组:
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"];
我想向后切片每个元素,例如:
I want to slice each element backwards, like:
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"].slice(-2);
所以它会返回:
arr = ["Toyo", "Hyund", "Hon", "Maz"];
有可能吗?或者有没有这样做?
Is it possible? or is there anyway of doing this?
推荐答案
你不能使用 slice
直接,因为它与数组有不同的含义,并会返回一个数组元素列表。
You can't use slice
directly, as it has a different meaning with an array and will return you a list of array elements.
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"]
arr.slice(0, -2) // returns the elements ["Toyota", "Hyundai"]
为了对每个元素进行切片,你可以使用 .map()
(在IE9 +上):
In order to do the slice on each element, you can use .map()
(on IE9+):
var out = arr.map(function(v) { return v.slice(0, -2) })
// or using underscore.js for wider compatibility
var out = _.map(arr, function(v) { return v.slice(0, -2) })
// or using a more modern arrow function
var out = arr.map(v => v.slice(0, -2))
或者,您可以使用循环:
Alternatively, you could just use a loop:
var i, out = []
for (i = 0; i < arr.length; ++i) {
out.push(arr[i].slice(0, -2))
}
或者,用更现代的语法:
or, in more modern syntax:
const out = new Array(arr.length)
for (let i = 0; i < arr.length; ++i) {
out[i] = arr[i].slice(0, -2)
}
这篇关于在Javascript中切片数组的每个字符串值元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文