8.7k

How do I check if an element is hidden in jQuery?

How do I toggle the visibility of an element using .hide() , .show() , or .toggle() ? How do I test if an element is visible or hidden ?

2008javascriptjquerydomvisibilitydisplay·3 重點答案·3.3M 次瀏覽
7.7k

How do I redirect to another webpage?

How can I redirect the user from one page to another using jQuery or pure JavaScript?

2009javascriptjqueryhttp-redirect·3 重點答案·8.2M 次瀏覽
7.7k

var functionName = function() {} vs function functionName() {}

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent. The previous de…

2008javascriptfunctionmethodssyntax·3 重點答案·1.2M 次瀏覽
7.6k

How do JavaScript closures work?

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand clos…

2008javascriptfunctionvariablesscopeclosures·3 重點答案·1.6M 次瀏覽
7.6k

How do I remove a property from a JavaScript object?

Given an object: let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; How do I remove the property regex to end up with the following myObject ? le…

2008javascriptobjectproperties·3 重點答案·3.4M 次瀏覽
6.7k

How do I return the response from an asynchronous call?

How do I return the response/result from a function foo that makes an asynchronous request? I am trying to return the value from the callback, as well as assigning the result to a…

2013javascriptajaxasynchronous·3 重點答案·2.2M 次瀏覽
6.4k

What is the difference between "let" and "var"?

ECMAScript 6 introduced the let declaration keyword . I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyw…

2009javascriptscopeecmascript-6varlet·3 重點答案·2.4M 次瀏覽
5.5k

How do I replace all occurrences of a string?

Given a string: string = "Test abc test test abc test test test abc test test abc"; This seems to only remove the first occurrence of abc in the string above: string = string.repl…

2009javascriptstringreplace·3 重點答案·4.6M 次瀏覽
5.5k

How do I create a GUID / UUID?

How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passin…

2008javascriptguiduuid·3 重點答案·3.3M 次瀏覽
5.5k

How can I validate an email address in JavaScript?

I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How…

2008javascripthtmlregexemail-validation·3 重點答案·4.9M 次瀏覽
5.2k

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. For example, if the age checkbox is checked, then I need to sh…

2009javascriptjqueryhtmlcheckbox·3 重點答案·5M 次瀏覽
5k

How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i…

2008javascriptarraysalgorithmtime-complexityjavascript-objects·3 重點答案·3.7M 次瀏覽
4.9k

How do I get a timestamp in JavaScript?

I want a single number that represents the current date and time, like a Unix timestamp .

2008javascriptdatetimetimestampdate-arithmetic·3 重點答案·4.7M 次瀏覽
4.6k

Setting "checked" for a checkbox with jQuery

I'd like to do something like this to tick a checkbox using jQuery : $(".myCheckBox").checked(true); or $(".myCheckBox").selected(true); Does such a thing exist?

2009javascriptjquerycheckboxselectedchecked·3 重點答案·3.9M 次瀏覽
4.5k

Why does Google prepend while(1); to their JSON responses?

Why does Google prepend while(1); to their (private) JSON responses? For example, here's a response while turning a calendar on and off in Google Calendar : while (1); [ ['u', [ […

2010javascriptjsonajaxsecurity·3 重點答案·612k 次瀏覽
4.5k

"Thinking in AngularJS" if I have a jQuery background?

Suppose I'm familiar with developing client-side applications in jQuery , but now I'd like to start using AngularJS . Can you describe the paradigm shift that is necessary? Here a…

2013javascriptjqueryangularjs·3 重點答案·858k 次瀏覽
4.4k

How can I insert an item into an array at a specific index?

I am looking for a JavaScript array insert method, in the style of: arr.insert(index, item) It should preferably be in jQuery, but any JavaScript implementation will do at this po…

2009javascriptarrays·3 重點答案·3.7M 次瀏覽
4.3k

How do I copy to the clipboard in JavaScript?

How do I copy text to the clipboard (multi-browser)? Related: How does Trello access the user's clipboard?

2008javascriptclipboardcopy-paste·3 重點答案·3.1M 次瀏覽
4.3k

How to round to at most 2 decimal places, if necessary

I'd like to round at most two decimal places, but only if necessary . Input: 10 1.7777777 9.1 Output: 10 1.78 9.1 How can I do this in JavaScript?

2012javascriptroundingdecimal-point·3 重點答案·5M 次瀏覽
4.2k

Sort array of objects by string property value

I have an array of JavaScript objects: var objs = [ { first_nom: 'Laszlo', last_nom: 'Jamf' }, { first_nom: 'Pig', last_nom: 'Bodine' }, { first_nom: 'Pirate', last_nom: 'Prentice…

2009javascriptarrayssortingcomparisonarray-of-dict·3 重點答案·3.5M 次瀏覽
4.1k

Checking if a key exists in a JavaScript object?

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist, and I try to access it, will it return false? Or throw an error?

2009javascriptarraysobject·3 重點答案·3.9M 次瀏覽
4.1k

How to loop through the items of an array in JavaScript?

In Java, you can use a for loop to traverse objects in an array as follows: String[] myStringArray = {"Hello", "World"}; for (String s : myStringArray) { // Do something } Can I d…

2010javascriptarraysloopsfor-loop·3 重點答案·5.6M 次瀏覽
4k

What is the JavaScript version of sleep()?

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function ? function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDat…

2009javascriptsleep·3 重點答案·5.4M 次瀏覽
3.9k

How do I test for an empty JavaScript object?

After an AJAX request, sometimes my application may return an empty object, like: var a = {}; How can I check whether that's the case?

2009javascriptjavascript-objects·3 重點答案·4.5M 次瀏覽
3.8k

Get the current URL with JavaScript?

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable…

2009javascripturl·3 重點答案·4M 次瀏覽
3.8k

How do I correctly clone a JavaScript object?

I have an object x . I'd like to copy it as object y , such that changes to y do not modify x . I realized that copying objects derived from built-in JavaScript objects will resul…

2009javascriptclonejavascript-objects·3 重點答案·2.6M 次瀏覽
3.6k

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following: var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; How do I loop through all of p 's elements ( p1 , p2 , p3 ...) and get t…

2009javascriptloopsfor-loopeach·3 重點答案·2.9M 次瀏覽
3.6k

How can I convert a string to boolean in JavaScript?

Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript? I have a hidden form in HTML that is updated based on a user's se…

2008javascriptboolean-expressionboolean-operationsstring-conversion·3 重點答案·3.7M 次瀏覽
3.6k

How do I format a date in JavaScript?

How do I format a Javascript Date object as a string? (Preferable format: 10-Aug-2010 )

2010javascriptdatedatetimedatetime-formatdate-formatting·3 重點答案·7.1M 次瀏覽
3.6k

pretty-print JSON using JavaScript

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

2011javascriptjsonpretty-print·3 重點答案·2M 次瀏覽
3.5k

What is the difference between call and apply?

What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function? const func = function() { alert("Hello world!"); }; func.apply(…

2009javascriptfunctionperformance·3 重點答案·844k 次瀏覽
3.4k

How can I merge properties of two JavaScript objects?

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to: var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } obj1.me…

2008javascriptjavascript-objects·3 重點答案·2.1M 次瀏覽
3.4k

How can I check if an object is an array?

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can l…

2011javascriptarraysjavascript-objects·3 重點答案·2.1M 次瀏覽
3.4k

Using async/await with a forEach loop

Are there any issues with using async / await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file. import fs from 'fs-promise' a…

2016javascriptnode.jspromiseasync-awaitecmascript-2017·3 重點答案·2.5M 次瀏覽
3.3k

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to pl…

2009javascriptjqueryevent-handlingdom-eventsevent-propagation·3 重點答案·951k 次瀏覽
3.2k

Is it possible to apply CSS to half of a character?

What I am looking for: A way to style one HALF of a character. (In this case, half the letter being transparent) What I have currently searched for and tried (With no luck): Metho…

2014javascripthtmlcss·3 重點答案·301k 次瀏覽
3.2k

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approac…

2008javascriptjquery·3 重點答案·880k 次瀏覽
3.2k

How can I upload files asynchronously with jQuery?

I would like to upload a file asynchronously with jQuery. $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "P…

2008javascriptjqueryajaxasynchronousxmlhttprequest·3 重點答案·1.5M 次瀏覽
3.1k

How can I check for "undefined" in JavaScript?

What is the most appropriate way to test if a variable is undefined in JavaScript? I've seen several possible ways: if (window.myVariable) Or if (typeof(myVariable) != "undefined"…

2010javascriptundefined·3 重點答案·3.8M 次瀏覽
3.1k

How to store objects in HTML5 localStorage/sessionStorage

I'd like to store a JavaScript object in HTML5 localStorage , but my object is apparently being converted to a string. I can store and retrieve primitive JavaScript types and arra…

2010javascripthtmllocal-storage·3 重點答案·1.5M 次瀏覽
3.1k

How do I modify the URL without reloading the page?

Is there a way I can modify the URL of the current page without reloading the page? I would like to access the portion before the # hash if possible. I only need to change the por…

2009javascripthtmlurlurl-rewritingfriendly-url·3 重點答案·2.2M 次瀏覽
3.1k

Length of a JavaScript object

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object(); myObject["firstname"] = "Gareth"; my…

2008javascriptobjectjavascript-objects·3 重點答案·3.1M 次瀏覽
3.1k

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery? I can get all of them like this: $("form :radio") How do I know which…

2009javascriptjqueryhtmljquery-selectorsradio-button·3 重點答案·2.6M 次瀏覽
3k

How do I detect a click outside an element?

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is…

2008javascriptjqueryclick·3 重點答案·1.8M 次瀏覽
3k

Open a URL in a new tab (and not a new window)

I'm trying to open a URL in a new tab, as opposed to a popup window. I've seen related questions where the responses would look something like: window.open(url,'_blank'); window.o…

2011javascripttabshref·3 重點答案·4.1M 次瀏覽
2.9k

Encode URL in JavaScript

How do you safely encode a URL using JavaScript such that it can be put into a GET string? var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "ht…

2008javascripturlencodeurlencode·3 重點答案·2M 次瀏覽
2.9k

Generate a string of random characters

I want a string of fixed length, composed of characters picked randomly from a set of characters e.g. [a-zA-Z0-9] . How can I do this with JavaScript?

2009javascriptstringrandom·3 重點答案·3.2M 次瀏覽
2.9k

How to append something to an array?

How do I append an object (such as a string or number) to an array in JavaScript?

2008javascriptarraysappend·3 重點答案·5.5M 次瀏覽
2.9k

Compare two dates with JavaScript

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.

2009javascriptdatedatetimecompare·3 重點答案·3.6M 次瀏覽
2.8k

How can I format a number with commas as thousands separators?

I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this?…

2010javascriptformattingnumbers·3 重點答案·2.3M 次瀏覽
2.7k

Scroll to an element with jQuery

I have this input element: <input type="text" class="textfield" value="" id="subject" name="subject"> Then I have some other elements, like other tag's & <textarea> tag's, etc...…

2011javascriptjqueryscroll·3 重點答案·3.2M 次瀏覽
2.7k

How can I determine if a variable is 'undefined' or 'null'?

How do I determine if a variable is undefined or null ? My code is as follows: var EmpName = $("div#esd-names div#name").attr('class'); if(EmpName == 'undefined'){ // DO SOMETHING…

2010javascriptjqueryvariablesnullundefined·3 重點答案·3.6M 次瀏覽
2.7k

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Moderator note: Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unne…

2018javascriptecmascript-6·3 重點答案·436k 次瀏覽
2.7k

How can I get query string values in JavaScript?

Is there a plugin-less way of retrieving query string values via jQuery (or without)? If so, how? If not, is there a plugin which can do so?

2009javascripturlpluginsquery-string·3 重點答案·5.5M 次瀏覽
2.7k

Set a default parameter value for a JavaScript function

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you…

2009javascriptfunctionparametersargumentsdefault-parameters·3 重點答案·1.5M 次瀏覽
2.7k

Adding a table row in jQuery

I'm using jQuery to add an additional row to a table as the last row. I have done it this way: $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>'); Are there limit…

2008javascriptjqueryhtml-table·3 重點答案·2.1M 次瀏覽
2.6k

Generate random number between two numbers in JavaScript

Is there a way to generate a random number in a specified range with JavaScript ? For example : a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5,…

2011javascriptrandom·3 重點答案·2.7M 次瀏覽
2.6k

Disable/enable an input with jQuery?

$input.disabled = true; or $input.disabled = "disabled"; Which is the standard way? And, conversely, how do you enable a disabled input?

2009javascriptjqueryhtml-inputdisabled-input·3 重點答案·2.7M 次瀏覽
2.6k

Validate decimal numbers in JavaScript - IsNumeric()

What's the cleanest, most effective way to validate decimal numbers in JavaScript? Bonus points for: Clarity. Solution should be clean and simple. Cross-platform. Test cases: 01.…

2008javascriptvalidationnumbers·3 重點答案·1.6M 次瀏覽
2.5k

Remove duplicate values from a JavaScript array

I have a very simple JavaScript array that may or may not contain duplicates. var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]; I need to remove the duplicates an…

2012javascriptjqueryarraysduplicatesunique·3 重點答案·3.4M 次瀏覽
2.5k

How to format numbers as currency strings?

I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this: $ 2,500.00 How can I do this?

2008javascriptformattingcurrencynumber-formatting·3 重點答案·3M 次瀏覽
2.5k

.prop() vs .attr()

So jQuery 1.6 has the new function prop() . $(selector).click(function(){ //instead of: this.getAttribute('style'); //do i use: $(this).prop('style'); //or: $(this).attr('style');…

2011javascriptjquerydomattrprop·3 重點答案·751k 次瀏覽
2.5k

What is JSONP, and why was it created?

I understand JSON, but not JSONP. Wikipedia's document on JSON is (was) the top search result for JSONP. It says this: JSONP or "JSON with padding" is a JSON extension wherein a p…

2010javascriptjsonjsonpterminology·3 重點答案·632k 次瀏覽
2.5k

How to create an array containing 1...N

I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime. var foo = []; for (var i = 1; i <= N; i++…

2010javascriptarraysrange·3 重點答案·2.9M 次瀏覽
2.5k

JavaScript check if variable exists (is defined/initialized)

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.)) if (elem) { // or…

2011javascriptfunctionvariablesinitializationundefined·3 重點答案·2.7M 次瀏覽
2.5k

JavaScript equivalent to printf/String.Format

I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() ( IFormatProvider for .NET). My basic requirement is a thousand sepa…

2009javascriptprintfstring.format·3 重點答案·2.6M 次瀏覽
2.5k

Get the size of the screen, current web page and browser window

How can I get windowWidth , windowHeight , pageWidth , pageHeight , screenWidth , screenHeight , pageX , pageY , screenX , screenY which will work in all major browsers?

2010javascripthtmljquerylayoutcross-browser·3 重點答案·2.3M 次瀏覽
2.5k

$(document).ready equivalent without jQuery

I have a script that uses $(document).ready , but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency. How can I implement my own…

2009javascriptjquerypageload·3 重點答案·1.4M 次瀏覽
2.4k

Get selected value in dropdown list using JavaScript

How do I get the selected value from a dropdown list using JavaScript? <form> <select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2<…

2009javascripthtml-select·3 重點答案·6.1M 次瀏覽
2.4k

How to get the children of the $(this) selector?

I have a layout similar to this, and would like to use a jQuery selector to select the child img inside the div on click. <div id="..."> <img src="..."> </div> To get the div , I'…

2008javascriptjqueryjquery-selectors·3 重點答案·2M 次瀏覽
2.4k

Iterate through object properties

var obj = { name: "Simon", age: "20", clothing: { style: "simple", hipster: false } } for(var propt in obj){ console.log(propt + ': ' + obj[propt]); } How does the variable propt…

2011javascriptloopsobject·3 重點答案·1.7M 次瀏覽
2.4k

What is the preferred syntax for defining enums in JavaScript?

What is the preferred syntax for defining enums in JavaScript? Something like: my.namespace.ColorEnum = { RED : 0, GREEN : 1, BLUE : 2 } // later on if(currentColor == my.namespac…

2008javascriptsyntaxenums·3 重點答案·1.3M 次瀏覽
2.4k

How can I programmatically navigate using React Router?

With React Router , I can use the Link element to create links which are natively handled by React Router. I see internally it calls this.context.transitionTo(...) . I want to do…

2015javascriptreactjsreact-router·3 重點答案·1.8M 次瀏覽
2.2k

Short circuit Array.forEach like calling break

[1,2,3].forEach(function(el) { if(el === 1) break; }); How can I do this using the new forEach method in JavaScript? I've tried return; , return false; and break . break crashes a…

2010javascriptarraysforeach·3 重點答案·1.9M 次瀏覽
2.2k

Detecting an "invalid date" Date instance in JavaScript

I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how: var d = new Date("foo"); console.log(d.toString()); // shows 'Invalid Da…

2009javascriptdate·3 重點答案·1.7M 次瀏覽
2.2k

What is the scope of variables in JavaScript?

What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if…

2009javascriptfunctionvariablesscopevar·3 重點答案·586k 次瀏覽
2.2k

Disable same origin policy in Chrome

Is there any way to disable the Same-origin policy on Google's Chrome browser?

2010javascriptajaxgoogle-chrome·3 重點答案·3.9M 次瀏覽
2.2k

How do I empty an array in JavaScript?

Is there a way to empty an array and if so possibly with .remove() ? For instance, A = [1,2,3,4]; How can I empty that?

2009javascriptarrays·3 重點答案·4.4M 次瀏覽
2.2k

How to decide when to use Node.js?

I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.js is. Considering how much I love working with jQuery and JavaScript in general, I can't he…

2011javascriptnode.jsweb-applications·3 重點答案·590k 次瀏覽
2.2k

Get the last item in an array

Here is my JavaScript code so far: var linkElement = document.getElementById("BackButton"); var loc_array = document.location.href.split('/'); var newT = document.createTextNode(u…

2010javascriptarrays·3 重點答案·3.7M 次瀏覽
2.2k

How does JavaScript .prototype work?

I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one…

2009javascriptdynamic-languagesprototype-oriented·3 重點答案·522k 次瀏覽
2.2k

Preview an image before it is uploaded

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image. How can I do th…

2010javascriptjqueryfile-upload·3 重點答案·1.9M 次瀏覽
2.2k

How to create a copy of a JavaScript array instead of a reference?

When copying an array in JavaScript to another array: var arr1 = ['a','b','c']; var arr2 = arr1; arr2.push('d'); console.log(arr1); //= ['a','b','c','d'] I realized that arr2 refe…

2011javascriptarraysdeep-copypass-by-value·3 重點答案·1.3M 次瀏覽
2.2k

How can I display a JavaScript object?

How do I display the content of a JavaScript object in a string format like when we alert a variable? The same formatted way I want to display an object.

2009javascriptserializationjavascript-objects·3 重點答案·2.6M 次瀏覽
2.1k

Writing to files in Node.js

I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?

2010javascriptnode.jsfileexpressfs·3 重點答案·2.2M 次瀏覽
2.1k

Loop inside React JSX

I'm trying to do something like the following in React JSX (where ObjectRow is a separate component): <tbody> for (var i=0; i < numrows; i++) { <ObjectRow/> } </tbody> I realize a…

2014javascriptreactjsjsx·3 重點答案·2.2M 次瀏覽
2.1k

Scroll to the top of the page using JavaScript?

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.

2009javascriptscroll·3 重點答案·2.6M 次瀏覽
2.1k

Turning off an ESLint rule for a specific line

In order to turn off a linting rule for a particular line in JSHint, we use the following rule: /* jshint ignore:start*/ $scope.someVar = ConstructorFunction(); /* jshint ignore:e…

2015javascriptjshinteslint·3 重點答案·1.9M 次瀏覽
2k

How does data binding work in AngularJS?

How does data binding work in the AngularJS framework? I haven't found technical details on their site . It's more or less clear how it works when data is propagated from view to…

2012javascriptangularjsdata-binding·3 重點答案·366k 次瀏覽
2k

How to merge two arrays in JavaScript and de-duplicate items

I have two JavaScript arrays: var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"]; I want the output to be: var array3 = ["Vijendra","Singh","Shakya"]; The output…

2009javascriptarraysmerge·3 重點答案·2.3M 次瀏覽
2k

Abort Ajax requests using jQuery

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?

2009javascriptjqueryajax·3 重點答案·733k 次瀏覽
2k

How do you use a variable in a regular expression?

I would like to create a String.replaceAll() method in JavaScript and think using a regex would be the most terse way to do it. However, I can't figure out how to pass a variable…

2009javascriptregex·3 重點答案·1.4M 次瀏覽
2k

From an array of objects, extract value of a property as array

I have JavaScript object array with the following structure: objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ]; I want to extract a field from each object, an…

2013javascriptjavascript-objects·3 重點答案·2M 次瀏覽
2k

How to detect a mobile device using jQuery

Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the bro…

2010javascriptjquerymobilebrowser-detection·3 重點答案·2M 次瀏覽
2k

Where should I put <script> tags in HTML markup?

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place thes…

2009javascripthtml·3 重點答案·915k 次瀏覽
1.9k

How to move an element into another element

I would like to move one DIV element inside another. For example, I want to move this (including all children): <div id="source"> ... </div> into this: <div id="destination"> ...…

2009javascriptjqueryhtml·3 重點答案·1.5M 次瀏覽
1.9k

What is the 'new' keyword in JavaScript?

The new keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language. What is…

2009javascriptnew-operator·3 重點答案·387k 次瀏覽
1.9k

How to access the correct `this` inside a callback

I have a constructor function which registers an event handler: function MyConstructor(data, transport) { this.data = data; transport.on('data', function () { alert(this.data); })…

2013javascriptcallbackthis·3 重點答案·660k 次瀏覽
1.9k

What is the difference between Bower and npm?

What is the fundamental difference between bower and npm ? Just want something plain and simple. I've seen some of my colleagues use bower and npm interchangeably in their project…

2013javascriptnpmbowerdependency-management·3 重點答案·340k 次瀏覽
1.9k

How do I remove a key from a JavaScript object?

Let's say we have an object with this format: var thisIsObject= { 'Cow' : 'Moo', 'Cat' : 'Meow', 'Dog' : 'Bark' }; I wanted to do a function that removes by key: removeFromObjectB…

2010javascript·3 重點答案·2.1M 次瀏覽
1.9k

Why does ++[[]][+[]]+[+[]] return the string "10"?

This is valid and returns the string "10" in JavaScript ( more examples here ): console.log(++[[]][+[]]+[+[]]) Why? What is happening here?

2011javascriptsyntaxjsfuck·3 重點答案·238k 次瀏覽
1.9k

'map' function for objects (instead of arrays)

I have an object: myObject = { 'a': 1, 'b': 2, 'c': 3 } I am looking for a native method, similar to Array.prototype.map that would be used as follows: newObject = myObject.map(fu…

2013javascriptnode.jsfunctional-programmingmap-function·3 重點答案·3M 次瀏覽
1.8k

How to check if a string "StartsWith" another string?

How would I write the equivalent of C#'s String.StartsWith in JavaScript? var haystack = 'hello world'; var needle = 'he'; haystack.startsWith(needle) == true Note: This is an old…

2009javascriptstringstartswith·3 重點答案·1.1M 次瀏覽
1.8k

How to measure time taken by a function to execute

I need to get execution time in milliseconds. Note : I originally asked this question back in 2008. The accepted answer then was to use new Date().getTime() However, we can all ag…

2008javascriptprofiling·3 重點答案·1.2M 次瀏覽
1.8k

Is JavaScript a pass-by-reference or pass-by-value language?

The primitive types (number, string, etc.) are passed by value. Still, objects are unknown because they can be both passed by value (in which case we consider that a variable hold…

2009javascriptpass-by-referencepass-by-value·3 重點答案·598k 次瀏覽
1.8k

What does "javascript:void(0)" mean?

<a href="javascript:void(0)" id="loginlink">login</a> I've seen such href s many times, but I don't know what exactly that means.

2009javascriptvoid·3 重點答案·2.9M 次瀏覽
1.8k

Stop setInterval call in JavaScript

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? I want the user to be able to stop the re…

2008javascriptdom-eventssetinterval·3 重點答案·1.5M 次瀏覽
1.8k

How to add days to Date?

How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay() ?

2009javascriptdate·3 重點答案·2.4M 次瀏覽
1.8k

Convert form data to JavaScript object with jQuery

How do I convert all elements of my form to a JavaScript object? I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over…

2009javascriptjqueryjsonserialization·3 重點答案·1.1M 次瀏覽
1.8k

JavaScript post request like a form submit

I'm trying to direct a browser to a different page. If I wanted a GET request, I might say document.location.href = 'http://example.com/q=a'; But the resource I'm trying to access…

2008javascriptformspostsubmit·3 重點答案·1.9M 次瀏覽
1.8k

Parse JSON in JavaScript?

I want to parse a JSON string in JavaScript. The response is something like var response = '{"result":true,"count":1}'; How can I get the values result and count from this?

2011javascriptjsonparsing·3 重點答案·2M 次瀏覽
1.8k

Get the values from the "GET" parameters (JavaScript)

I have a URL with some GET parameters as follows: www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 I need to get the whole value of c . I tried to read the URL, but I got only m2 . How d…

2009javascripturlurl-parameters·3 重點答案·2.9M 次瀏覽
1.8k

How to add a class to an HTML element with JavaScript?

I have an element that already has a class: <div class="someclass"> ... </div> How can i add a class to the div (not replace, but add) with JavaScript?

2009javascripthtmldom-manipulation·3 重點答案·2.8M 次瀏覽
1.7k

JavaScript set object key by variable

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so: var key = "hap…

2012javascript·3 重點答案·1.5M 次瀏覽
1.7k

Sorting an array of objects by property values

I've got the following objects using AJAX and stored them in an array: var homes = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id":…

2009javascriptarrayssorting·3 重點答案·1.6M 次瀏覽
1.7k

Differences between Lodash and Underscore.js

Why would someone prefer either the Lodash or Underscore.js utility library over the other? Lodash seems to be a drop-in replacement for underscore, the latter having been around…

2012underscore.jsjavascriptlodash·3 重點答案·374k 次瀏覽
1.7k

How do I debug Node.js applications?

How do I debug a Node.js server application? Right now I'm mostly using alert debugging with print statements like this: sys.puts(sys.inspect(someVariable)); There must be a bette…

2009javascriptnode.jsdebugginggoogle-chrome-devtools·3 重點答案·569k 次瀏覽
1.7k

Difference between == and === in JavaScript

What is the difference between == and === in JavaScript? I have also seen != and !== operators. Are there more such operators?

2009javascriptcomparison-operatorsequality-operatoridentity-operator·2 重點答案·1.1M 次瀏覽
1.7k

How to convert a string to number in TypeScript?

Given a string representation of a number, how can I convert it to number type in TypeScript? var numberString: string = "1234"; var numberValue: number = /* what should I do with…

2013javascripttypescript·3 重點答案·2.8M 次瀏覽
1.7k

How do I find out which DOM element has the focus?

I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and ho…

2009javascriptdom·3 重點答案·993k 次瀏覽
1.7k

Convert a Unix timestamp to time in JavaScript

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it? For example, in HH/MM/SS format.

2009javascriptdatetimetime-format·3 重點答案·2.7M 次瀏覽
1.7k

Event binding on dynamically created elements?

I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off . This…

2008javascriptjqueryeventsunobtrusive-javascript·3 重點答案·1.1M 次瀏覽
1.7k

Remove empty elements from an array in Javascript

How do I remove empty elements from an array in JavaScript? Is there a straightforward way, or do I need to loop through it and remove them manually?

2008javascriptarrays·3 重點答案·1.9M 次瀏覽
1.7k

How does the 'Access-Control-Allow-Origin' header work?

Apparently, I have completely misunderstood its semantics. I thought of something like this: A client downloads JavaScript code MyCode.js from http://siteA - the origin . The resp…

2012javascriptcross-domaincors·3 重點答案·2.8M 次瀏覽
1.7k

How to find the sum of an array of numbers

Given an array [1, 2, 3, 4] , how can I find the sum of its elements? (In this case, the sum would be 10 .) I thought $.each might be useful, but I'm not sure how to implement it.

2009javascriptjqueryarrays·3 重點答案·3.2M 次瀏覽
1.6k

Merge/flatten an array of arrays

I have a JavaScript array like: [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]] How would I go about merging the separate inner arrays into one like: ["$6", "$12",…

2012javascriptarraysmultidimensional-arraymergeflatten·3 重點答案·1.3M 次瀏覽
1.6k

What is the "right" JSON date format?

I've seen so many different standards for the JSON date format: "\"\\/Date(1335205592410)\\/\"" .NET JavaScriptSerializer "\"\\/Date(1335205592410-0500)\\/\"" .NET DataContractJso…

2012javascriptjson·3 重點答案·2.1M 次瀏覽
1.6k

How to compare arrays in JavaScript?

I'd like to compare two arrays... ideally, efficiently. Nothing fancy, just true if they are identical, and false if not. Not surprisingly, the comparison operator doesn't seem to…

2011javascriptarraysjson·3 重點答案·1.9M 次瀏覽
1.6k

Read environment variables in Node.js

Is there a way to read environment variables in Node.js code? Like for example Python's os.environ['HOME'] .

2011javascriptnode.jsenvironment-variables·3 重點答案·993k 次瀏覽
1.6k

Is there a "null coalescing" operator in JavaScript?

Is there a null coalescing operator in Javascript? For example, in C#, I can do this: String someString = null; var whatIWant = someString ?? "Cookies!"; The best approximation I…

2009javascriptoperatorsnull-coalescing-operatornull-coalescing·3 重點答案·487k 次瀏覽
1.6k

How can I select an element by name with jQuery?

I have a table column I’m trying to expand and hide. jQuery seems to hide the <td> elements when I select it by class but not by the element’s name . For example: $(".bold").hide(…

2009javascriptjqueryhtmldomjquery-selectors·3 重點答案·2.4M 次瀏覽
1.6k

Where does npm install packages?

Can someone tell me where can I find the Node.js modules, which I installed using npm ?

2011javascriptnode.jslocationnpm·3 重點答案·1.4M 次瀏覽
1.5k

How to manage a redirect request after a jQuery Ajax call

I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out,…

2008javascriptjqueryajaxhttp-redirect·3 重點答案·1.2M 次瀏覽
1.5k

Why don't self-closing script elements work?

What is the reason browsers do not correctly recognize: <script src="foobar.js" /> <!-- self-closing script element --> Only this is recognized: <script src="foobar.js"></script>…

2008javascripthtmlinternet-explorerxhtml·3 重點答案·177k 次瀏覽
1.5k

Sending command line arguments to npm script

The scripts portion of my package.json currently looks like this: "scripts": { "start": "node ./script.js server" } ...which means I can run npm start to start the server. So far…

2012javascriptnode.jsnpm·3 重點答案·1.2M 次瀏覽
1.5k

Where can I find documentation on formatting a date in JavaScript?

I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats. Xmas95 = new Date("25 Dec, 1995 23:15:00") Xmas95 = new Date("2009 06 12,12:52…

2009javascriptdatedatetime-formatjava-dateformattime-format·3 重點答案·1.6M 次瀏覽
1.5k

Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array? I am using the following code, but it always returns the count of checked checkbox…

2010javascriptjqueryhtmlcheckbox·3 重點答案·2.8M 次瀏覽
1.5k

Object comparison in JavaScript

What is the best way to compare objects in JavaScript? Example: var user1 = {name : "nerd", org: "dev"}; var user2 = {name : "nerd", org: "dev"}; var eq = user1 == user2; alert(eq…

2009javascriptobjectcomparisonobject-comparison·3 重點答案·1.6M 次瀏覽
1.5k

Safely turning a JSON string into an object

Given a string of JSON data, how can I safely turn that string into a JavaScript object? Obviously I can do this unsafely with something like: var obj = eval("(" + json + ')'); bu…

2008javascriptjsonparsing·3 重點答案·1.5M 次瀏覽
1.5k

What are these three dots in React doing?

What does the ... do in this React (using JSX) code and what is it called? <Modal {...this.props} title='Modal heading' animation={false}>

2015javascriptreactjsspread-syntax·3 重點答案·668k 次瀏覽
1.5k

Check if element exists in jQuery

How do I check if an element exists if the element is created by .append() method? $('elemId').length doesn't work for me.

2011javascriptjquery·3 重點答案·1.8M 次瀏覽