如果在“ for in”循环中

时间:2019-02-25 08:42:11

标签: javascript for-loop

检查两个对象是否相等:

我不确定我的代码如何运行以及如何解决此问题。

在areEqual函数中,我正在检查两个对象的“值”。

如果它们相等-> isEqual = true-> for循环应继续 如果其中一个值不相等-> isEqual = false并退出循环。

但是我没有得到想要的结果。 我在这里完全不了解什么逻辑?

    function Address (street, city, zipCode) {
    this.street = street; 
    this.city = city; 
    this.zipCode = zipCode; 
}

let address1 = new Address('a', 'b', 'c'); 
let address2 = new Address('a', 'd', 'c'); 


//checking for equality between two objects
function areEqual(address1, address2){  
    let isEqual = true; 
        for(let key in address1) {
            if(address1[key] === address2[key])
                isEqual = true; 
            else
                isEqual = false
                break; 
        }
    if(isEqual) return 'They are equal'; 
        else return 'They are not equal'; 

}

console.log(areEqual(address1, address2)); 

2 个答案:

答案 0 :(得分:1)

您的代码等同于:

  public void sendMessage(String message){
        Log.d("TAG","message :"+message+", session id:"+sessionId);
        MessageInput input = new MessageInput.Builder()
                .messageType("text")
                .text(message)
                .build();
        MessageOptions options = new MessageOptions.Builder(assistanID, sessionId)
                .input(input)
                .build();
        assistant.message(options).enqueue(new ServiceCallback<MessageResponse>() {
            @Override
            public void onResponse(MessageResponse response) {
                System.out.println(response);
                Gson gson = new Gson();

                GsonWatson gsonparse = gson.fromJson(String.valueOf(response), GsonWatson.class);
                mainActivity.messageRecievedFromAssistant(gsonparse.getOutput().getGeneric().get(0).getText());
            }
            @Override
            public void onFailure(Exception e) {

            }
        });
    }





 android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at okhttp3.Dns$1.lookup(Dns.java:40)
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:214)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at com.ibm.watson.developer_cloud.service.security.IamTokenManager.callIamApi(IamTokenManager.java:187)
        at com.ibm.watson.developer_cloud.service.security.IamTokenManager.requestToken(IamTokenManager.java:108)
        at com.ibm.watson.developer_cloud.service.security.IamTokenManager.getToken(IamTokenManager.java:78)
        at com.ibm.watson.developer_cloud.service.WatsonService.setAuthentication(WatsonService.java:375)
        at com.ibm.watson.developer_cloud.service.WatsonService.createCall(WatsonService.java:206)
        at com.ibm.watson.developer_cloud.service.WatsonService.createServiceCall(WatsonService.java:240)
        at com.ibm.watson.developer_cloud.assistant.v2.Assistant.message(Assistant.java:151)
        at com.XXX.IBMwatson.sendMessage(IBMwatson.java:78)
        at com.XXX.ibmwatson.MainActivity$onCreate$1.onClick(MainActivity.kt:39)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

您需要将else条件包装在if (address1[key] === address2[key]) isEqual = true; else isEqual = false break; 中。目前,它在第一次迭代时就跳出了循环

{}

如果格式化代码,则可以避免这些类型的错误。每个代码编辑器都有此功能的快捷方式。

注意:由于您具有function Address(street, city, zipCode) { this.street = street; this.city = city; this.zipCode = zipCode; } let address1 = new Address('a', 'b', 'c'); let address2 = new Address('a', 'd', 'c'); let address3 = new Address('x', 'y', 'z'); let address4 = new Address('x', 'y', 'z'); //checking for equality between two objects function areEqual(address1, address2) { let isEqual = true; for (let key in address1) { if (address1[key] === address2[key]) isEqual = true; else { isEqual = false break; } } if (isEqual) return 'They are equal'; else return 'They are not equal'; } console.log(areEqual(address1, address2)); console.log(areEqual(address3, address4));的构造函数,因此该代码将起作用。但是请注意,这只是检查Address中的键是否具有与address1相同的值。如果您比较一个像address2这样的空对象,它将记录areEqual({}, address2),因为它永远不会进入They are equal循环。因此,如果forObject.keys(address1).length

相同,则可以添加其他检查

答案 1 :(得分:0)

您具有isEquls的默认值:true,因此如果任何键对都不等于将isEquls设置为false并中断循环:

function Address (street, city, zipCode) {
    this.street = street; 
    this.city = city; 
    this.zipCode = zipCode; 
}

let address1 = new Address('a', 'd', 'd'); 
let address2 = new Address('a', 'd', 'c'); 


//checking for equality between two objects
function areEqual(address1, address2){  
    let isEqual = true; 
        for(let key in address1) {
            if(address1[key] !== address2[key])
            {
                isEqual = false
                break; 
            }
        }
    if(isEqual) return 'They are equal'; 
        else return 'They are not equal'; 

}

console.log(areEqual(address1, address2));