小编Har*_*ish的帖子

理解数组时我错过了什么?

将数组分配给另一个变量时,将传递引用而不是值.当您使用==运算符比较两个数组并且它返回时,会确认这一点true

var a = [[1,2],[3,4],[5,6]];
var b = a; // b = [[1,2],[3,4],[5,6]]
var c = [].concat(a); // c = [[1,2],[3,4],[5,6]]

a == b; //true
a == c; //false
Run Code Online (Sandbox Code Playgroud)

通过上面的输入,当我修改数组时b,它会改变数组a,但不是c.

b.push([7,8]); // b = [[1,2],[3,4],[5,6], [7,8]]
a; //a = [[1,2],[3,4],[5,6], [7,8]]
c; //c = [[1,2],[3,4],[5,6]]
Run Code Online (Sandbox Code Playgroud)

但是当我在下面做的时候,它会发生变异c.

b[0].push(5); // b = [[1,2,5],[3,4],[5,6], [7,8]]
a; //a = [[1,2,5],[3,4],[5,6], [7,8]]
c; //c = [[1,2,5],[3,4],[5,6]]
Run Code Online (Sandbox Code Playgroud)

为什么会这样?使用改变数组的数组方法会发生此行为.

javascript

8
推荐指数
1
解决办法
240
查看次数

为什么getPrototypeOf()在JavaScript中返回错误的构造函数?

var protoRabbit = {size: "small"};
var fastRabbit = Object.create(protoRabbit);
console.log(Object.getPrototypeOf(fastRabbit));
Run Code Online (Sandbox Code Playgroud)

上面的代码段打印:

对象{size:"small"}

这不应该打印protoRabbit {size:"small"}吗?我的理解中缺少什么?

javascript prototype

5
推荐指数
1
解决办法
66
查看次数

Javascript:仍然被instanceof运算符搞糊涂了

文章如下定义的instanceof:

instanceof运算符测试对象在其原型链中是否具有构造函数的prototype属性.

这是一个公平的解释,生活很好,直到我从Eloquent Javascript这本书中看到这个代码:

function TextCell(text) {
  this.text = text.split("\n");
}

TextCell.prototype.minWidth = function() {
  return this.text.reduce(function(width, line) {
    return Math.max(width, line.length);
  }, 0);
}

TextCell.prototype.minHeight = function() {
  return this.text.length;
}

TextCell.prototype.draw = function(width, height) {
  var result = [];
  for (var i = 0; i < height; i++) {
    var line = this.text[i] || "";
    result.push(line + repeat(" ", width - line.length));
  }
  return result;
}

function RTextCell(text) {
  TextCell.call(this, text);
}

RTextCell.prototype = Object.create(TextCell.prototype);

RTextCell.prototype.draw …
Run Code Online (Sandbox Code Playgroud)

javascript inheritance instanceof

5
推荐指数
1
解决办法
176
查看次数

又一个Call vs Apply查询

当我尝试运行以下代码时:

function flatten(a) {
  return [].slice.call(arguments).reduce(function(acc, val) {
    return acc.concat(Array.isArray(val) ? flatten.call(null, val) : val);
  }, []);
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

未捕获RangeError:超出最大调用堆栈大小

但如果我使用flatten.apply而不是flatten.call,它的工作完美.(深度压平输入数组).

除了这个link1link2之外,我还阅读了其他一些博客和文章,以了解其行为的原因.我要么找不到答案,要么就是忽略了它.(原谅我的眼睛,如果在后一种情况下)

当然,这两者之间的根本区别在于:

apply - 要求可选参数为数组

call - 要求显式列出可选参数

通常,函数可以采用任何类型的参数 - 基元和非基元.所以,我的问题是:

  1. 调用方法的可选参数之一可以是类型Array还是其他非基本类型?

  2. 为什么上面的代码超过了调用堆栈,何时call使用?

编辑:由于call使用了2 种方法,我的描述含糊不清.我做了修改以澄清.

javascript

2
推荐指数
1
解决办法
50
查看次数

标签 统计

javascript ×4

inheritance ×1

instanceof ×1

prototype ×1