[英]JavaScript How to replace first element of an array with each element of another array
[英]get first 3 elements of array then another 3 element then another 3 element in javascript
嗨,我有一个包含 9 个元素的数组 - array = ['a','b','c','d','e','f','g','h','i']
。 我有一个符合条件的变量。
data==='test' ?
data1 = array.slice(0,3) :
data==='test1' ?
data1 = array.slice(3,6) :
data==='test2' ?
data1 = array.slice(6,9) :
data1 = data;
如果数据与测试匹配,则 data1 应为['a','b','c']
。 如果数据与 test1 匹配,则 data1 应该是['d','e','f']
。 如果数据与 test1 匹配,则 data1 应该是['g','h','i']
。
如果数据等效于测试,但在 test1 和 test2 中没有获得正确的数据后,我将正确获取数据 1。 在 test1 和 test2 中没有得到。
有没有办法实现这一目标?
可以使用switch
语句吗? // 为了更好的可读性
const array = ['a','b','c','d','e','f','g','h','i']
const data = 'test1';
let data1;
switch (data) {
case 'test':
data1 = array.slice(0,3);
break;
case 'test1':
data1 = array.slice(3,6);
break;
case 'test2':
data1 = array.slice(6,9);
break;
default:
data1 = data;
break;
}
我会使用test
字符串后面的数字作为乘数来获得所需的部分;
const data = ['a','b','c','d','e','f','g','h','i']; console.log(getDataPart('test')); console.log(getDataPart('test1')); console.log(getDataPart('test2')); function getDataPart(str) { // Get number behind 'test', fallback to '0' const n = (str.length <= 4) ? 0 : str.substring(4); // Return desired part return data.slice((n*3), (n*3) + 3) }
您可以将位置存储在对象内,并使用数据值获取位置:
const data = "test1"; const array = ['a','b','c','d','e','f','g','h','i'] const pos = { "test": [0,3], "test1": [3,6], "test2": [6,9] } const data1 = array.slice(...pos[data]); console.log(data1);
const array = ['a','b','c','d','e','f','g','h','i'] const data = 'test2'; const data1 = data==='test' ? array.slice(0,3) : (data==='test1' ? array.slice(3,6) : (data==='test2' ? array.slice(6,9) : data)); console.log(data1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.