在JavaScript中测试变量是否未定义的最合适方法是什么?我见过几种可能的方法:
if (window.myVariable)
Run Code Online (Sandbox Code Playgroud)
要么
if (typeof(myVariable) != "undefined")
Run Code Online (Sandbox Code Playgroud)
要么
if (myVariable) //This throws an error if undefined. Should this be in Try/Catch?
Run Code Online (Sandbox Code Playgroud) 我有一个用Node.js编写的Web服务器,我想用特定的文件夹启动.我不确定如何在JavaScript中访问参数.我正在运行这样的节点:
$ node server.js folder
Run Code Online (Sandbox Code Playgroud)
这server.js是我的服务器代码.Node.js帮助说这是可能的:
$ node -h
Usage: node [options] script.js [arguments]
Run Code Online (Sandbox Code Playgroud)
我如何在JavaScript中访问这些参数?不知怎的,我无法在网上找到这些信息.
我希望JavaScript函数具有可选参数,我将其设置为默认值,如果未定义该值,则使用该参数.在Ruby中你可以这样做:
def read_file(file, delete_after = false)
# code
end
Run Code Online (Sandbox Code Playgroud)
这是否适用于JavaScript?
function read_file(file, delete_after = false) {
// Code
}
Run Code Online (Sandbox Code Playgroud) 所以jQuery 1.6具有新功能prop().
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');
})
Run Code Online (Sandbox Code Playgroud)
或者在这种情况下,他们做同样的事情?
如果我也有转用prop(),所有的旧attr()电话,如果我切换到1.6将打破?
UPDATE
selector = '#id'
$(selector).click(function() {
//instead of:
var getAtt = this.getAttribute('style');
//do i use:
var thisProp = $(this).prop('style');
//or:
var thisAttr = $(this).attr('style');
console.log(getAtt, thisProp, thisAttr);
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id='id' style="color: red;background: orange;">test</div>Run Code Online (Sandbox Code Playgroud)
(另见这个小提琴:http://jsfiddle.net/maniator/JpUF2/)
控制台会记录getAttribute作为一个字符串,并attr作为一个字符串,但prop作为一个CSSStyleDeclaration,为什么?这对我未来的编码有何影响?
如何从jQuery的下拉列表中获取所选文本(而不是选定的值)?
如果我有一个JavaScript对象,请说
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
Run Code Online (Sandbox Code Playgroud)
是否有内置或接受的最佳实践方法来获取此对象的长度?
如何以易于阅读(针对人类读者)格式显示JSON?我主要是寻找缩进和空白,甚至可能是颜色/字体样式等.
有没有办法在不重新加载页面的情况下修改当前页面的URL?
如果可能的话,我想访问#hash 之前的部分.
我只需要在域之后更改部分,因此它不像我违反了跨域策略.
window.location.href = "www.mysite.com/page2.php"; // Sadly this reloads
Run Code Online (Sandbox Code Playgroud) $input.disabled = true;
Run Code Online (Sandbox Code Playgroud)
要么
$input.disabled = "disabled";
Run Code Online (Sandbox Code Playgroud)
哪种标准方式?而且,相反,如何启用禁用输入?
javascript ×10
jquery ×3
arguments ×1
arrays ×1
attr ×1
dom ×1
friendly-url ×1
function ×1
html ×1
html-input ×1
json ×1
node.js ×1
parameters ×1
pretty-print ×1
prop ×1
undefined ×1
url ×1