Typescript固定数组的默认值



寻找一种方法来创建对象数组,有一个固定的大小3填充它的默认值,但当我来推入数组,它应该取代默认值。

:

声明一个数组,用"默认值"字符串填充数组

["default value", "default value", "default value"]

我现在将一些文本推入这个初始数组,并期望如下:

["Added Data", "Default value", "Default Value"]

我将更多的数据压入这个数组,并期望如下:

["Added Data", "Added Data", "Default Value"]

再次将更多数据压入该数组,并期望如下:

["Added Data", "Added Data", "Added Data"]

所以最终的结果应该是如果压入一个数据,那么数组的其余部分应该保持默认值,除非我将所有三个数据都压入数组。

注意:这个例子是一个字符串数组只是为了显示一个例子,但我正在寻找的解决方案是对象数组。Array.fill ()方法对于JavaScript不可变值(如字符串、数字和布尔值)非常有效。具有对象的数组,数组中的每个槽指的是相同的对象,这不是我要找的。我希望每个对象都是唯一的

您可以扩展Array类,使其具有您描述的行为…

class FixedArray extends Array {
/**
* Contruct a fixed-length Array
* @param int length - length of the array
* @param mixed default_value - The default value for empty slots
*/
constructor(length, default_value) {
super(length);
this.default_value = default_value;
super.fill(default_value);
}
/**
* "Push" items onto the begining of the array (unshift)
* @params ...args mixed - values to put in the array
*/
push(...args) {
args.forEach(arg => {
super.pop();
super.unshift(arg);
});
}
/**
* Pop an item off the end of the array 
* and replace it with the default value
*/
pop(){
super.pop();
super.push(this.default_value);
}
/**
* Shift an item off the start of the array 
* and replace it with the default value
*/
shift(){
super.shift();
super.unshift(this.default_value);
}
}
var arr = new FixedArray(4, 'default value');
console.log(arr);
arr.push('new value');
console.log(arr);
arr.push('new value');
console.log(arr);
arr.pop();
console.log(arr);

为了解决数组填充方法的问题,你可以添加一个方法来复制你放进去的任何值…

/**
* Fill the array with copies of whatever arguments are provided.
* Fills by value, not by reference.
*/
fill(...args){
args.forEach(arg=>{
let copy = JSON.parse(JSON.stringify(arg));
this.push(arg);
});
}

对于基本数据类型默认值,遵循下面的语法

const numList = new Array(10).fill(0)
console.log(numList)
console.log('Total items: ' + numList.length)

<<p>对象/strong>的默认值,遵循下面的语法

const objList = new Array(10).fill(0).map(()=> ({ a: 1, b: 2 }))
console.log(objList)
console.log('Total items: ' + objList.length)

用默认的唯一对象值创建和填充数组:

const tuple = new Array(3).fill(0).map(() => ({ foo: "bar" }))
// or
const defaultObject = { foo: "bar" }
const tuple = new Array(3).fill(0).map(() => ({ …defaultObject }))

添加新项,并保持数组大小不变

function addTo(tuple, newItem) {
tuple.unshift(newItem) // add new item to beginning 
tuple.pop() // remove old item at the end
}

最新更新