正如你所看到的,这段代码相当简单,我实际上理解了大部分内容,但唯一令我困惑的部分是if if语句,更具体地说是null的使用。从我所读到的,null成为值或一个立场,不像undefined,它只是那个,未定义。那么为什么在这种情况下使用null?
function range(start, end, step) {
if (step == null) step = 1;
var array = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
array.push(i);
} else {
for (var i = start; i >= end; i += step)
array.push(i);
}
return array;
}
function sum(array) {
var total = 0;
for (var i = 0; i < array.length; i++)
total += array[i];
return total;
}
console.log(range(1, 10))
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55
答案 0 :(得分:1)
step
将被取消定义,之所以这样做是因为弱比较null == undefined
是真的,但如果我们使用更严格的评估,即{{1}我们弄错了。
答案 1 :(得分:0)
如果在没有step
参数的情况下调用该函数,默认情况下会将其设置为1
。
所以这里:
console.log(range(1, 10)
/ → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
没有&#34;步骤&#34;包括..但输出显示步骤已设置为1.在以下示例中,包括步骤IS,以便使用该值。
答案 2 :(得分:0)
在javascript函数中,如果没有提供某个参数,则它是未定义的。这里的代码应该是
Glide.with(context)
.load(uri)
.asBitmap()
.into(new SimpleTarget<Bitmap>(width, height) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
// add image to the imageView here
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// you are given the error drawable
}
});
使用严格的比较总是更好的做法。由于if (step === undefined) step = 1;
也null==undefined
,因此代码有效。你应该修改上面提到的代码。