微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript-使用多个变量作为对象属性

如何解决Javascript-使用多个变量作为对象属性

object.js

 ob_start();
 imagejpeg( $img,NULL,100 );
 imagedestroy( $img );
 $i = ob_get_clean();

 echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";

if语句显示涉及对象所需信息的随机性。

结果1: 当@Component({ selector: 'my-component' }) export class LinkInitComponent implements OnInit { public linkKind: 'phoneLink' | 'emailLink' | 'routerLink' | 'simpleLink' | 'simpleText'; ngOnInit(): void { this.linkKind = this.initLinlType(); } private initLinlType(): 'phoneLink' | 'emailLink' | 'routerLink' | 'simpleLink' | 'simpleText' { return 'simpleText' } } var a = "level_2"; var b = "level_3"; var c; const nums = [1,2,3,4]; const num_1 = nums[Math.floor(Math.random() * nums.length)]; const num_2 = nums[Math.floor(Math.random() * nums.length)]; console.log({ num_1,num_2 }); if (num_1 <= num_2) { c = [a]; } else { c = [a][b]; } /** * Lets say I make a database call,the result is from a promise I use '.then()' * eg: * ... * .then(level_1 => { * let final; * final = level_1[c] * res.statusCode(200).json({ final }) * })... * * This is what I'm trying to achieve where I can determine the object property * how deep in the object I would like to go before I get the object.*/ const level_1 = { level_2: { level_3: "level_3",level_4: "level_4",level_5: { level_6: "level_6",},}; console.log("\nPrint 1:\n",level_1[a]); console.log("\nPrint 2:\n",level_1[a][b]); console.log("\nPrint 3:\n",level_1[c]);

时,此方法不起作用
c

结果2: 如果只有[a][b],则$ node object.js { num_1: 4,num_2: 1 } Print 1: { level_3: 'level_3',level_4: 'level_4',level_5: { level_6: 'level_6' } } Print 2: level_3 Print 3: undefined 会很好用

c

如何让[a]工作?如您所见,$ node object.js { num_1: 2,num_2: 3 } Print 1: { level_3: 'level_3',level_5: { level_6: 'level_6' } } Print 2: level_3 Print 3: { level_3: 'level_3',level_5: { level_6: 'level_6' } } c返回了undefined,这已经困扰了我一段时间,如果有人可以帮助我,它将使我的代码非常有效。

解决方法

如果您希望能够合并属性,请使用属性数组,或通过.连接所有属性。然后,要获取嵌套的值,请使用Accessing nested JavaScript objects and arays by string path中的方法之一:

const level_1 = {
  level_2: {
    level_3: "level_3",level_4: "level_4",level_5: {
      level_6: "level_6",},};

var a = "level_2";
var b = "level_3";

const c = [a,b];
const getNested = (obj,props) => props.reduce((a,prop) => a[prop],obj);

console.log(level_1[a]);
console.log(level_1[a][b]);
console.log(getNested(level_1,c));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。