javascript - 在对象文字内分配数值不会引发任何错误
问题描述
考虑以下代码:
let logged = 1;
let x = {logged} //{logged: 1}
x['logged']; // 1
x['logged']['index']; //undefined
x['logged']['index'] = 0;
x; // {logged: 1}
x['logged']['index']; //undefined
所以,我的问题是:不是
x[logged]['index']
做类似的事情1['index']
。不应该给出类似cannot index a numeric literal
错误的东西吗?x[logged]['index'] = 0;
,这不会引发任何错误,就好像元素存储在某个地方一样,但是,这个值存储在哪里?如图所示line 6
,x 的值仍然是{logged: 1}
。为什么它不抛出错误?为什么 x[logged]['index'] 仍然未定义?
我在 nodejs 终端上测试了这个,节点版本为 14.16.0
解决方案
不确定我上面的评论是否真的为您完全阐明了这个问题。
我编写了一个小程序,可能有助于可视化发生的情况。请注意,我正在对原始值而不是常规属性查找进行方法查找 - 但这都是一样的,并且可以更好地说明发生了什么。
function captureThis() {
return this
}
(function setUpObjectPrototype() {
if (Object.prototype.captureThis !== undefined) throw new Error("Couldn't set up Object prototype properly.")
Object.prototype.captureThis = captureThis
process.nextTick(() => delete Object.prototype.captureThis)
})()
var number = 1
var thisObject = number.captureThis()
console.log("Is thisObject an object? " + (typeof thisObject == "object"))
console.log("Is number still just a number? " + (typeof number == "number"))
console.log("Is thisObject an instance of Number? " + (thisObject instanceof Number))
// Output
// Is thisObject an object? true
// Is number still just a number? true
// Is thisObject an instance of Number? true
请注意,数字变量在任何时候都不会实际强制转换为对象——创建了一个临时对象来包装数字变量中包含的值。该对象实际上从未分配给变量 - 除非它像在这个小程序中一样被捕获。
希望这会有所帮助。
推荐阅读
- java - Jar Runtime 中带有 Selenium webdriver 的 Java Gradle 错误
- php - 如何检查/查找字符串中是否有多个字母 | PHP
- python - 使用阈值对点是否在指定区域内进行分类 - python
- python - 编译 QML 源代码以使用 PySide2 进行保护
- c# - mongodb C# 使用查找和方面进行计数
- laravel - 如何将html表格行与1个参考和多个项目结合起来?
- pandas - 在 Dask 中,如何删除未在另一列的所有值中重复的数据?
- sql - 为什么我的查询可以使用 RIGHT() 和 LEFT() 函数,但不能使用 LIKE 谓词?
- vba - 搜索表格旁边的标题样式时 Range.Find 失败
- java - 将二维数组传递给另一个类,但无法返回对象