这段代码是否正确? [英] Is this code correct?

查看:68
本文介绍了这段代码是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在努力学习JS,你可以看到。 在typeof中使用2个参数是否可以?此外,将使用'if(!output)return false;'实际上工作以验证是否找到相应的元素? 程序有效(显示答案),但我只是想确定错误检查是否正确。我希望这是有道理的!我打算粘贴整个代码,以防万一:



  //   today.js#2  
// 此脚本指示当前日期和时间。

// 此函数用于更新HTML元素的文本。
// 该函数需要两个参数:元素的ID和文本消息。
function setText(elementId,message){
' use strict';

// 更新了参数,因此它们不能是空字符串 - bullet#1
// 更新了参数,因此它们也可以是一个数字 - 项目符号#2
if (( typeof elementId == ' string' || Number
&&( typeof message == ' string' || Number ))
if (( typeof elementId !== ' '
&&( typeof 消息!== ' )){

// 获取段落的引用:
var output = 文档 .getElementById(elementId);

// 验证是否找到了相应的元素 - bullet#3
if (!output) return false ;

// 更新段落的innerText或textContent属性:
if (output.textContent!== undefined ){
output.textContent = message ;
} else {
output.innerText = message;
}

} // 主要IF结束。

} // setText()函数结束。

// 页面加载后调用此函数:
function init(){
' use strict';
var today = new 日期();
var message = ' 现在它是' + today.toLocaleDateString();
消息+ = ' at' + today.getHours()+ ' :' + today.getMinutes();

// 更新页面:
setText(' output',message);

} // init()函数结束。
window .onload = init;






$ b $嗯,我在这里。这是我正在使用的教科书:



引用:

验证函数的参数:

if ((typeof elementId =='string')

&&(typeof message =='string')){

此功能只有在收到两者时才有效值和两者都是类型

字符串(从技术上讲,消息可能是一个数字)。







然后作业是:

更新today.js,以便消息也可以是一个数字。并更新它,使它不能是一个空字符串。



我用这个空字符串:



  if (( typeof  elementId!== < span class =code-string>' '
&&( typeof message!== ' '))







但是没有多少研究让我知道如何添加以便消息可以是一个数字。这是我在JS的第一个月,第3次任务,所以我感谢你给我任何指导!

解决方案

当然不能有2个参数一种。一个简单的原因是:typeof在语法上是操作数,而不是函数,因此,正式地说,它可以有操作数,没有参数。只有一个操作数,没有ifs没有但是: https://developer.mozilla.org / en-US / docs / Web / JavaScript / Reference / Operators / typeof [ ^ ]。



此外,拥有更多这个唯一的操作数是没有任何意义的。



这个问题在以下意义上没有任何意义:代码只有在其目的已知的情况下才是正确的或错误的。当然,在JavaScript的情况下,它应该是词法正确的。一个逗号逗号或分号可以使整个脚本无效,而不仅仅是错误点。 (JavaScript不是逐个执行的语言,正如许多人错误地认为的那样;如果代码在词汇级别上有错误,则不执行任何操作,甚至不执行其中某些正确的部分。)



现在,这是你执行的类型检查的一个问题:例如,让我们假设某个对象是字符串,但是你可以拼错单词'string'。即使对于字符串,检查也总是会失败,没有什么可以告诉你真正的原因是拼写错误的类型名称。所以,我设计了以下技术:

  if  typeof  message ==  typeof  ' '){ / *   ... * / } 





我会很高兴看到有人建议更好的东西。 [结束编辑]



同时,在几乎所有情况下,开发都不应该依赖于类型检查。毕竟,JavaScript在这个级别上的类型太少了。即使我实际上使用上面显示的技术,我只在一些特殊情况下,例如在我的字符串格式或对象转储方法中。最好依赖于类型已知的技术。



对于对象类型的对象,可以检查两个对象是否具有相同的来源检查他们的构造函数:

  var  obj1 = [ 1  2  3 ]; 
var obj2 = [ 4 5 < /跨度>];
var ofTheSameType12 = obj1。 constructor === obj2。构造; // true

function MyObject(id){ this .id = id; .comment = ' some comment' ; }
var obj3 = new MyObject( 1 );
var obj4 = new MyObject( 200 < /跨度>);
var ofTheSameType34 = obj3。 constructor === obj3。构造; // true
// true,尽管obj3和obj4在逻辑上是不同的

function MyOtherObject(id){ this .id = id; .comment = ' some comment' ; }
var obj5 = new MyObject( 1 );
var obj6 = new MyOtherObject( 1 < /跨度>);
var ofTheSameType56 = obj5。 constructor === obj6。构造; // false
var ofTheSameType56NonStrict = obj5。 constructor == obj6。 constructor ; // false
// false,尽管obj5和obj6在逻辑上是相同的



-SA

Hi All,
I'm struggling with JS, as you can see. Is it okay to use 2 parameters in a typeof? Also, will using 'if (!output) return false;' actually work to Verify that corresponding element is found? The program "works" (displays an answer), but I just want to be certain that the error checks are correct. I hope that made sense! I'm going to paste the whole code, just in case:

// today.js #2
// This script indicates the current date and time.

// This function is used to update the text of an HTML element.
// The function takes two arguments: the element's ID and the text message.
function setText(elementId, message) {
    'use strict';
    
    // Updated arguments so they cannot be an empty string - bullet #1
    // Updated arguments so they can also be a number - bullet #2
    if ( (typeof elementId == 'string' || Number)
            && (typeof message == 'string' || Number) )
    if ( (typeof elementId !== '')
            && (typeof message !== '') ){
  
        // Get a reference to the paragraph:
        var output = document.getElementById(elementId);
        
        //Verify that corresponding element is found - bullet #3
        if (!output) return false;
      
        // Update the innerText or textContent property of the paragraph:
		if (output.textContent !== undefined) {
			output.textContent = message;
		} else {
			output.innerText = message;
		}
    
    } // End of main IF.

} // End of setText() function.

// Call this function when the page has loaded:
function init() {
    'use strict';
    var today = new Date();
    var message = 'Right now it is ' + today.toLocaleDateString();
    message += ' at ' + today.getHours() + ':' + today.getMinutes();

    // Update the page:
    setText('output', message);
    
} // End of init() function.
window.onload = init;




Well, I'm in over my head here. This is from the textbook that I am using:

Quote:
Validate the function’s parameters:
if ( (typeof elementId == ‘string’)
&& (typeof message == ‘string’) ) {
This function can only work if it receives both values and both are of type
String (well, technically, the message could be a number).



Then the assignment was to:
Update today.js so that message can also be a number. And to update it so that it can't be an empty string.

I used this for the empty string:

if ( (typeof elementId !== '')
            && (typeof message !== '') )




but no amount of research gave me an indication of how to add so that the message could be a number. This is my first month, 3rd assignment in JS, so I thank you for any guidance that you can give me!

解决方案

Of course there cannot be "2 parameters in a typeof". One simple reason is this: typeof is, syntactically, operand, not a function, so, formally, it can have operand, no "parameters". Only one operand, no ifs no buts: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof[^].

Moreover, having more then this only operand cannot make any sense.

The question makes no sense in the following sense: code can be right or wrong only if its purpose is known. Of course, it should be, in case of JavaScript, lexically correct. One wring comma or semicolon can make whole script invalid, not just the point with the error. (JavaScript is not the language which is executed one by one, as many mistakenly think; if the code has an error on lexical level, nothing executes, not even some correct part of it.)

Now, here is one problem with the type check you perform: for example, let's assume that some object is, say, string, but you could misspell the word 'string'. The check will always fail, even for strings, and nothing can tell you that the real reason is misspelled type name. So, I devised the following technique:

if (typeof message == typeof '') { /* ... */ }



[EDIT] I'll be very glad to see if someone suggests something better. [END EDIT]

At the same time, in nearly all cases, development should not rely on the type check. After all, JavaScript has too few types distinguished on this level. Even though I actually use the technique shown above, I only do it in some special cases, such as in my string formatting or object dump methods. It's better to rely on techniques where the type is exactly known.

For objects of the type 'object', you can check up that the two objects have the same origin checking up their constructors:

var obj1 = [1, 2, 3];
var obj2 = [4, 5];
var ofTheSameType12 = obj1.constructor === obj2.constructor; // true

function MyObject(id) { this.id = id; this.comment = 'some comment'; }
var obj3 = new MyObject(1);
var obj4 = new MyObject(200);
var ofTheSameType34 = obj3.constructor === obj3.constructor; // true
// true, despite the fact that obj3 and obj4 are logically different

function MyOtherObject(id) { this.id = id; this.comment = 'some comment'; }
var obj5 = new MyObject(1);
var obj6 = new MyOtherObject(1);
var ofTheSameType56 = obj5.constructor === obj6.constructor; // false
var ofTheSameType56NonStrict = obj5.constructor == obj6.constructor; // false
// false, despite the fact that obj5  and obj6 are logically identical


—SA


这篇关于这段代码是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆