本文介绍了使用[]运算符时,在Typescript 1.6.2中从内置数组扩展的类不会更新长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我读到:
...
一些例子:
// Extend built-in types
class MyArray extends Array<number> { }
class MyError extends Error { }
...
但是在扩展Array时,使用[]运算符设置值时不会更新length属性。推送功能工作正常,但我需要[]运算符。
However when extending Array, length property is not updated while using [] operator to set values. Push function works fine, but I need [] operator.
我的例子:
class ExtendedArray<T> extends Array<T> {}
var buildinArray = new Array<string>();
var extendedArray = new ExtendedArray<string>();
buildinArray.push("A");
console.log(buildinArray.length); // 1 - OK
buildinArray[2] = "B";
console.log(buildinArray.length); // 3 - OK
extendedArray.push("A");
console.log(extendedArray.length); // 1 - OK
extendedArray[2] = "B";
console.log(extendedArray.length); // 1 - FAIL
console.dir(extendedArray); // both values, but wrong length
我做错了什么?问题出在哪里?
Am I doing something wrong? Where is the problem?
推荐答案
您的代码转换为此JavaScript代码:
Your code translates to this JavaScript code:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ExtendedArray = (function (_super) {
__extends(ExtendedArray, _super);
function ExtendedArray() {
_super.apply(this, arguments);
}
return ExtendedArray;
})(Array);
var buildinArray = new Array();
var extendedArray = new ExtendedArray();
buildinArray.push("A");
console.log(buildinArray.length); // 1 - OK
buildinArray[2] = "B";
console.log(buildinArray.length); // 3 - OK
extendedArray.push("A");
console.log(extendedArray.length); // 1 - OK
extendedArray[2] = "B";
console.log(extendedArray.length); // 1 - FAIL
console.dir(extendedArray); // both values, but wrong length
[]
问题是括号表示法不是作为复制数组
原型的一部分而复制的:
The problem is that the bracket notation is not copied as part of copying of Array
prototype:
[]
有一个深入的。
这篇关于使用[]运算符时,在Typescript 1.6.2中从内置数组扩展的类不会更新长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!