简体   繁体   English

如何在 Object 中创建自执行匿名 function?

[英]How to create self-executing anonymous function in Object?

in my object在我的 object

let obj = {
  name:["Harry","Scren","Docis","Altab"],
  age:[32,44,22,55]
}

I need to write down a self executing anonymous function in object that, when i call any member of the object it will execute that self executing anonymous function and it will check whether the length of both array (name and age) are equal or not, If not equal then throw an error.....I need to have something like I need to write down a self executing anonymous function in object that, when i call any member of the object it will execute that self executing anonymous function and it will check whether the length of both array (name and age) are equal or not,如果不相等,则抛出错误.....我需要类似的东西

let obj = {
  name:["Harry","Scren","Docis","Altab"],
  age:[32,44,22,55],

  (function(){
    if(name.length != age.length){
      throw new Error('both name and age 's length are not equal')
     }
    }()) // But this is not possible to create in object I have just showed down what I wanted to create
}

How to create something like that in javascript object??如何在 javascript object 中创建类似的东西?

I'm not sure, but I think that's not possible... But let me ask a question: why you have an obj containing two arrays?我不确定,但我认为这是不可能的......但让我问一个问题:为什么你有一个包含两个 arrays 的 obj? Hasn't more sense having an array of the obj which each element of the array contains one name and one age?拥有一个 obj 数组,其中每个元素都包含一个名称和一个年龄,这不是更有意义吗? I'll show you我会给你看

const people = [
    { name: "Pearson 1", age: 20 },
    { name: "Pearson 2", age: 20 },
    { name: "Pearson 3", age: 20 },
    { name: "Pearson 4", age: 20 },
]

So you do not have to check the length since every obj has its own name and age field.因此,您不必检查长度,因为每个 obj 都有自己的名称和年龄字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM