Javascript字符串数组样对象行为 [英] Javascript String Array-Like-Object behaviour

查看:48
本文介绍了Javascript字符串数组样对象行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Chrome开发者控制台中运行上述代码时,没有收到任何错误.但是,当通过加载在网页上的 js 运行相同的代码时,我会收到此异常-无法在字符串"some string"上创建属性"name"

When I run above code in Chrome dev console, I do not get any error. But when same code runs via js loaded on a webpage I receive this exception - Cannot create property 'name' on string 'some string'

有人可以告诉我为什么在上述两种情况下会有不同的行为吗?

Can someone please tell me why there is different behaviour in above 2 cases?

推荐答案

您的网页必须在严格模式下运行该代码段,在这种模式下,分配给字符串的属性将引发错误:

Your webpage must be running that snippet of code in strict mode, in which assigning to properties of a string will throw an error:

'use strict';
const str = 'foo';
str.bar = 'bar';

在草率模式下,它只会无声地失败:

In sloppy mode, it'll just fail silently:

const str = 'foo';
str.bar = 'bar';

这篇关于Javascript字符串数组样对象行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆