简体   繁体   English

有人可以用简单的英语解释我的对象代码中特定部分的情况吗?

[英]Can someone please explain in plain english what is going on in a particular part of my code for objects?

although it is a very simple code, I would like to get a full understanding of what is happening in my condition: 尽管这是一个非常简单的代码,但我想全面了解自己的情况:

let getFreqOn = function(string){

    //set a variable for object

    let object = {}

    for (let key = 0; key < string.length; key++){

        // if (object.hasOwnProperty(string[key])) {

        // if (object[string[key]]) {

        // if (object[string[key]] !== undefined) {  

        if (string[key] in object) { 

            object[string[key]]++
        }
        else{
            object[string[key]] = 1
        }
    }
    return object
}

My main concern would be the first condition, I understand what it is they do but I cant put in to plain English how it is working. 我主要关心的是第一个条件,我知道他们在做什么,但我不能说白话它是如何工作的。 For example if (string[key] in object) is basically telling my that if a specific property is in the empty object I defined, then I will set then it will be set as the property and incremented. 例如,如果(对象中的string [key])基本上告诉我,如果特定属性位于我定义的空对象中,那么我将进行设置,然后将其设置为该属性并递增。 But what I'm trying to wrap my head around is that the object is empty, so how can the property be in the object? 但是我想绕开的是该对象为空,那么该属性如何在对象中?

Hoping someone can enlighten me on the conditions that I commented out as well. 希望有人能对我提出的条件也有所启发。 Sorry for the noob question. 对不起,菜鸟问题。

First, the in operator returns a boolean result. 首先, in运算符返回布尔结果。 It checks whether the string on the left is present as a property name in the object on the right. 它检查左侧的字符串是否作为属性名称出现在右侧的对象中。

Thus 从而

if (string[key] in object)

asks whether that single character of the string is in use as a property name in the object. 询问是否将该字符串的单个字符用作对象中的属性名称。 As you observed, the very first time through the loop that cannot possibly be true, because the object starts off empty. 正如您所观察到的那样,第一次循环可能无法实现,因为对象从空开始。

Thus the if test is false , so the else part runs. 因此, if test为false ,则else部分运行。 There, the code still refers to object[string[key]] , but it's a simple assignment. 那里,代码仍然引用object[string[key]] ,但这是一个简单的赋值。 An assignment to an object property works whether or not the property name is already there; 无论对象名称是否已经存在,对对象属性的分配都会起作用。 when it isn't, a new object property is implicitly created. 如果不是,则会隐式创建一个新的对象属性。

The key difference is right there in the two different statements from the two parts of the if - else : 关键的区别就在if - else的两个部分的两个不同的语句中:

  object[string[key]]++; // only works when property exists

  object[string[key]] = 1; // works always

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

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