关于javascript对象的点操作符和[]操作符

本文探讨了一种在JavaScript中给对象属性赋值的特殊方式,即使用计算得到的数值作为属性名。通过实例详细解释了如何利用这种方法解决两数之和的问题,并对比了点符号与方括号在属性赋值上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前两天在写一个javascript对象时,遇到了一个有点特殊的写法,我学艺不精,所以之前都没有遇到过,瞬间就懵逼了。内容是这样的:

var twoSum = function(nums, target){
    var saved={};
    var result=[];
    for(var i=0; i< nums.length; i++){
      if(saved.hasOwnProperty(nums[i])){
        result[0] = saved[nums[i]] ;
        result[1] = i;
        return result
      }
      saved[target - nums[i]] = i;
    }
  };
在代码中有这样的一句:

saved[target-nums[i]] = i ;

这个的意思是给对象一个属性赋值,但是这个属性是一个数字,哈哈,这个就很奇怪了。

第一,对象也可以用数组来做属性名;

第二,对象在使用点.操作符来赋值时,数字是错误的,并不能成功。

就因为这个原因,我自己在测试的时候,一直都不正确,在网上找了些列子也没有这个方法,就在csdn的论坛中发了一个帖子。得到了大家的回复,很感谢。

在帖子中是这样说的


(版主大神的回答,清晰明了,感觉自己的javascript还是很low的)


(其他大神的解释,也很清楚明了)

总结:

在对象中,可以使用点和[] 方法来添加和查找属性,但是点有其局限性,在选择中,属性名要符合规则,不规则的属性名不能使用点。可以使用[] 。

Rebuild started: Project: Project *** Using Compiler &#39;V6.22&#39;, folder: &#39;E:\Keil_v5\ARM\ARMCLANG\Bin&#39; Rebuild target &#39;Target 1&#39; assembling startup_stm32f10x_md.s... Start/core_cm3.c(445): error: non-ASM statement in naked function is not supported 445 | uint32_t result=0; | ^ Start/core_cm3.c(442): note: attribute is here 442 | uint32_t __get_PSP(void) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(465): error: parameter references not allowed in naked functions 465 | "BX lr \n\t" : : "r" (topOfProcStack) ); | ^ Start/core_cm3.c(461): note: attribute is here 461 | void __set_PSP(uint32_t topOfProcStack) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(479): error: non-ASM statement in naked function is not supported 479 | uint32_t result=0; | ^ Start/core_cm3.c(476): note: attribute is here 476 | uint32_t __get_MSP(void) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(499): error: parameter references not allowed in naked functions 499 | "BX lr \n\t" : : "r" (topOfMainStack) ); | ^ Start/core_cm3.c(495): note: attribute is here 495 | void __set_MSP(uint32_t topOfMainStack) __attribute__( ( naked ) ); | ^ 4 errors generated. compiling core_cm3.c... compiling misc.c... compiling system_stm32f10x.c... compiling stm32f10x_adc.c... compiling stm32f10x_dac.c... compiling stm32f10x_exti.c... compiling stm32f10x_dbgmcu.c... compiling stm32f10x_dma.c... compiling stm32f10x_crc.c... compiling stm32f10x_cec.c... compiling stm32f10x_bkp.c... compiling stm32f10x_can.c... compiling stm32f10x_flash.c... compiling stm32f10x_pwr.c... compiling stm32f10x_fsmc.c... compiling stm32f10x_
03-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值