lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | All , This is the code : Find a working example here : http : //plnkr.co/edit/57LS6oXPfqccAWf6uqQV ? p=previewMy question is what 's the difference between the last two ? I 'm accessing the object method in the same way , the only difference is the way it 's being called.Why does it return a difference result ? First t... | var Person = function ( name ) { this.name = name ; this.printName = function ( ) { console.log ( `` My name is `` + this.name ) ; } } ; var p = new Person ( `` Steve '' ) ; var funcRef = p [ `` printName '' ] ; p.printName ( ) ; //Worksp [ `` printName '' ] ( ) ; //WorksfuncRef ( ) ; //returns incorrect value | Javascript `` this '' scope giving different result depending on the way it is called |
JS | I am creating a very basic object in JavaScript and looping thru its properties , displaying property name : In IE and FireFox it produces expected result : But in Chrome same code producesAny idea why ? Does keyword name hold some significance in Chrome ? | var name = { ' A ' : 'DataA ' , ' B ' : 'DataB ' , ' C ' : 'DataC ' , 'D ' : 'DataD ' , ' E ' : 'DataE ' } for ( var propName in name ) { document.getElementById ( 'result ' ) .innerHTML += propName + ' & nbsp ; ' } A B C D E 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Iterating thru Object properties produces different results in different browsers |
JS | I have a categories array : I need to retrieve the subCategories array based on the id of the category.This return the entire category object , how can I change it to only return the subCategories array ? | { id : 1 , catName : `` test '' , subCategories : Array ( 2 ) } const subCategories = categoriesWithSub.filter ( category = > { return category.id === departments.catId ; } ) ; | Get sub array based on array value |
JS | http : //jsfiddle.net/gfuKS/5/Why at the second iteration transitions [ 0 ] .property equals `` background-color '' ? | var transitionInitial = { property : `` none '' } ; var rules = [ `` color '' , `` background-color '' ] ; var transitions = [ ] ; for ( var k = 0 ; k < rules.length ; k++ ) { transitions [ k ] = transitionInitial ; transitions [ k ] .property = rules [ k ] ; alert ( transitions [ 0 ] .property ) ; } | javascript array objects |
JS | Is there a way to expose an objects ' prototypes through another object ? In this code , the 'bar ' object is set up with prototype inheritance -- but exposing bar loses the inheritance of 'shoutAge'.However , the 'boo ' object has the prototype declared inside of it and the outside function has access to the method 's... | var foo = function ( ) { var foo = { bar : bar , boo : boo } return foo ; function bar ( age ) { this.age = age ; } bar.prototype.shoutAge = function ( ) { alert ( 'My age is ' + this.age ) ; } function boo ( age ) { this.age = age ; boo.prototype.shoutAge = function ( ) { alert ( 'My age is ' + this.age ) ; } } } var ... | Expose prototypes in object |
JS | I 'm using the latest Typescript version :2.6.2.I 'm encountering a bizarre situation where if I do foo ( { a:1 , b:2 } ) - things do n't work whereas if I do : foo ( { b:2 , a:1 } ) - they do work.I have a generic class , an interface which has 2 properties and a function.Here is the code : I get an error : But If I c... | class MyClass < T > { value : T ; next ( value : T ) : void { } } export enum StateKey { backlogItems='backlogItems ' } export interface State { backlogItems : number [ ] ; [ key : string ] : any } class A { private subj = new MyClass < State > ( ) ; public set < T > ( name : StateKey , state : T ) { this.subj.next ( {... | Typescript mind the order of instantiation in an Object literal ? |
JS | I have an API that returns the following : How do I return this correctly with players in the object and also paging info so they are separate keys ? | { 'data ' : { players : [ { id : 1 , name : 'harry ' } , { id : 2 , name : 'barry ' } ... ] , } , 'paging ' : { current : 1 , totalPages : 10 , } } getPlayers ( type : string ) : Observable < Player [ ] > { return this.get ( myApiURL ) .pipe ( map ( result = > { 'players ' : result.data.map ( player = > { player._dead ... | How to return observable with RxJS in proper format with additional separate paging data |
JS | This is continuation of My Old QuestionThis is my function which creates a new student object : I would like to create a copy of the object when it is initialized inside that object : I came up with this : But the problem is its giving me a infinite loop of copies of current object in baseCopy ; ANd also it is automati... | function student ( id , name , marks , mob , home ) { this.id = id ; this.name = name ; this.marks = marks ; this.contacts = { } ; this.contacts.mob = mob ; this.contacts.home = home ; this.toContactDetailsString = function ( ) { return this.name + ' : '+ this.mob + ' , '+ this.home } } function student ( id , name , m... | Can I preserve a copy of an object , inside that object when its created - Continued : |
JS | Let 's say you 've got three arrays of objects : The goal is to use a1 as a source , and add an id field to the elements of a2 and a3 with corresponding name fields in a1 . What is an efficient way of accomplishing this ? ( Note : 'efficient ' here meaning 'something more elegant than loops-within-loops-within-loops ' ... | let a1 = [ { id : 1 , name : 'foo ' } , { id : 2 , name : 'bar ' } , { id : 3 , name : 'baz ' } ] let a2 = [ { name : 'foo ' } , { name : 'bar ' } ] let a3 = [ { name : 'bar ' } , { name : 'baz ' } ] a2 : [ { id : 1 , name : 'foo ' } , { id : 2 , name : 'bar ' } ] a3 : [ { id : 2 , name : 'bar ' } , { id : 3 , name : '... | Efficiently merging fields from one array into two other arrays |
JS | I need a web socket client server exchange between Python and JavaScript on an air-gapped network , so I 'm limited to what I can read and type up ( believe me I 'd love to be able to run pip install websockets ) . Here 's a bare-bones RFC 6455 WebSocket client-server relationship between Python and JavaScript . Below ... | < script > const message = { name : `` ping '' , data : 0 } const socket = new WebSocket ( `` ws : //localhost:8000 '' ) socket.addEventListener ( `` open '' , ( event ) = > { console.log ( `` socket connected to server '' ) socket.send ( JSON.stringify ( message ) ) } ) socket.addEventListener ( `` message '' , ( even... | Why does client.recv ( 1024 ) return an empty byte literal in this bare-bones WebSocket Server implementation ? |
JS | Consider I have the below webpage written in HTML ( body section only ) : Now , if I replace the innerHTML of document.body from JavaScript with say , a div , so that the body part becomes : ... then is the fn object eligible for garbage collection if no references to it exist anywhere in the rest of the code ( any con... | < body > < p > ... < /p > < script > function fn ( ) { // do stuff } < /script > < /body > < body > < div > ... < /div > < /body > | Is inline javascript garbage collected when document body is replaced ? |
JS | Some one please shed light on this when doing bitwise operation in javascript I get:65527|34359738368 = > 65527Is it possible to handle this in javascript ? From mysql command line : And more importantly its less than 2 ^ 36What I read from this SO Q is that int in javascript support max 2^53 value . I might be missing... | select 65527|34359738368 ; + -- -- -- -- -- -- -- -- -- -+| 65527|34359738368 |+ -- -- -- -- -- -- -- -- -- -+| 34359803895 |+ -- -- -- -- -- -- -- -- -- -+ select ( 65527|34359738368 ) < pow ( 2,36 ) ; + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +| ( 65527|34359738368 ) < pow ( 2,36 ) |+ -- -- -- -- -- -- -- -- ... | Why this bitwise operation is failing in Javascript |
JS | I 've had a function such as called in a TouchableOpacity 's onPress prop like this : [ ... ] onPress= { functionOne.bind ( this , 'text ' ) } [ ... ] and it worked.On another component , I have a function such as which I pass to the component that has the first function via props . Something like this : < MiddleCompon... | const functionOne = parameterOne = > { [ ... ] } const functionTwo = parameterTwo = > { [ ... ] } | How to call for more than one functions in onPress prop ? |
JS | I have function : The above code works correctly.The above function enlarges and reduces the font size on my website.I need to limit the function of this function to a maximum of 3 times the size of the font . The font size reduction ( lower font size ) can not be smaller than its original ( original size ) .How to do ... | function changeFontSize ( points ) { var e = document.getElementsByTagName ( `` BODY '' ) [ 0 ] ; var style = window.getComputedStyle ( e ) ; var size = style.getPropertyValue ( 'font-size ' ) ; size = size.replace ( `` px '' , `` '' ) ; size = size * 1 ; size = size + points ; //if ( size < = 0 & & size < = 3 ) { e.st... | Function to change font size in js . how to add zooming limit ? |
JS | I inherited some code with a line that I do n't understand.What exactly is happening inside the .each function ? I 've never seen this ( var ) used this way before . | function updateQty ( ) { obj.find ( '.inputAmount ' ) .html ( qty ) ; input.val ( qty ) ; $ .each ( change_actions , function ( ) { this ( qty ) ; } ) ; } | Use of `` this '' as a function ? |
JS | I have broken this problem down into it 's simplest form . Basically I have a directive that , for the demo , does n't yet really do anything . I have a div with the directive as an attribute . The values within the div , which come from an object array , are not displayed . If I remove the directive from the div , the... | app.controller ( 'MainCtrl ' , function ( $ scope ) { $ scope.tooltips = [ { `` id '' :1 , '' warn '' : true } , { `` id '' :2 , '' warn '' : false } , { `` id '' :3 , '' warn '' : true } , { `` id '' :4 , '' warn '' : true } ] ; } ) ; app.directive ( `` cmTooltip '' , function ( ) { return { scope : { cmTooltip : `` =... | Data from directive not displaying within ng-repeat |
JS | The problem is that when ever i combine two functions that : gets all the id 's of the HTML tags of the websitesearches the array for `` Bad Words '' ( AKA . `` Hack '' , '' Hacker '' etc ... ) Code 1 : Code 2 : Of course Code 2 would be in a new function already tried but no success : ( and it would be edited to the n... | var eleng=document.documentElement.getElementsByTagName ( '* ' ) .length -1 ; var i=0 ; var id= [ ] ; function allids ( ) { if ( i < eleng ) { id.push ( document.documentElement.getElementsByTagName ( '* ' ) [ i ] .id ) ; if ( id [ i ] == `` || id [ i ] == ' ' ) { i++ ; allids ( ) ; } else { console.log ( id [ i ] ) ; ... | Javascript - String Searching , What will fix it ? |
JS | Common advice is to keep your CSS and JS files external . The reason : What you lose in the additional HTTP request* , you often gain back by not having to download cacheable static content ( which CSS and JS usually is ) .However , the smaller your external file , the more penalizing the additional HTTP request -- eve... | External File Size Average Gain -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1KB -3.7ms 2KB -3.7ms 4KB -4.0ms 8KB -3.0ms 16KB -2.7ms 32KB 1.0ms 64KB 2.7ms 128KB 10.0ms 256KB 493.7ms 512KB 1047.0ms 1024KB 2569.7ms | Considering only page speed , at what point is CSS or JS big enough to externalize |
JS | I have a reactive form in Angular which gets file format as text inputEg : .txt , .zip , .tar.gzI needed to convert those inputs as an array list . With the help of @ danday74 , I can able to do that . here is the code : The output generated by the code is [ `` txt '' , '' zip '' , '' tar.gz '' ] , which is what I expe... | < input type= '' text '' name= '' formats '' formControlName= `` formats '' > const input = `` .txt , .zip , .tar.gz '' const parts = input.split ( ' ' ) const output = parts.map ( x = > x.replace ( ' , ' , `` ) .replace ( ' . ' , `` ) ) console.log ( output ) | Remove . and , in the beginning/end of every element from the array list in Angular 6 |
JS | I am new to Javascript and NRRD Loader , in nrrd loader we can change the index value of a slice using the slider Consider I need update value of slicesX at same time with the same slider | sliceY = volume.extractSlice ( ' y ' , Math.floor ( volume.RASDimensions [ 1 ] /2 ) ) ; scene3.add ( sliceY.mesh ) ; gui.add ( sliceY , 'index ' , 0 , volume.RASDimensions [ 1 ] , 1 ) .name ( 'indexY ' ) .onChange ( function ( ) { sliceY.repaint.call ( sliceY ) ; } ) ; sliceX = volume.extractSlice ( ' x ' , Math.floor ... | How can i update two slice with same silde in nrrd loader |
JS | Using Ajax , I 've created a sort of console that allows me to execute some PHP functions dynamically.It looks like this The problem is that after a bunch of commands , the console becomes hard to read . So I 've created a javascript function , named `` wipe ( ) ; '' , which clears the < div > containing the console.I ... | echo ' < script > wipe ( ) ; < /script > ' ; var xmlhttp = new XMLHttpRequest ( ) ; var span = document.getElementById ( `` screen '' ) ; function send ( data ) { window.setInterval ( function ( ) { var elem = document.getElementById ( 'screen ' ) ; xmlhttp = new XMLHttpRequest ( ) ; xmlhttp.open ( `` GET '' , `` ./_rc... | javascript from ajax does n't get proper execution |
JS | The mere declaration of a function to an object leads to its invocationI would expect , that the declared function a.xyz only gets invoked when I call it : What is wrong with my assumption ? | var a = { } ; a.xyz = new function ( ) { alert ( `` dosomething '' ) ; } a.xyz ( ) ; | javascript - why is declared function invoked at runtime |
JS | I have the following code , which I took and modify from hereHere is my jsfiddle in actionI am currently developing a user interaction that needs these bubbles , exactly 5 bubbles that gravitate to the center of the screen . The thing is that I know how many times a user will click on each of these bubbles . The thing ... | var width = 500 , height = 500 , padding = 1.5 , // separation between same-color circles clusterPadding = 4 , // separation between different-color circles maxRadius = 40 ; var n = 5 , // total number of circles m = 1 ; // number of distinct clusters var color = d3.scale.category10 ( ) .domain ( d3.range ( m ) ) ; // ... | After a few clicks the animation freezes , why ? |
JS | I would like to draw a point and after 1 sec or so I would like to draw the next point . Is this somehow possible : I already tried : Unfortunately , this is not working . It just draws the whole line immediately . | function simulate ( i ) { setTimeout ( function ( ) { drawPoint ( vis , i , i ) ; } , 1000 ) ; } for ( var i = 1 ; i < = 200 ; ++i ) simulate ( i ) ; function drawPoint ( vis , x , y ) { var svg = vis.append ( `` circle '' ) .attr ( `` cx '' , function ( d ) { console.log ( x ) ; return 700/2+x ; } ) .attr ( `` cy '' ,... | How to animate drawing a sequence of line segments |
JS | I am trying to turn an array of objects into another array of objects by grouping by a specific value and adding that value as label and taking it out of the object in the new array.Input : So for instance I have this array of objects : Expected : I am looking to try and figure out how I can get to this , where there i... | let tech = [ { id : 1 , grouping : `` Front End '' , value : `` HTML '' } , { id : 2 , grouping : `` Front End '' , value : `` React '' } , { id : 3 , grouping : `` Back End '' , value : `` Node '' } , { id : 4 , grouping : `` Back End '' , value : `` PHP '' } , ] ; [ { label : `` Front End '' , options : [ { id : 1 , ... | Javascript - group array of objects by common values with label |
JS | I 'm trying to learn some jQuery , and I setup a test page with the following code : The idea is I can put something in the textarea and click either `` encode '' or `` decode '' , and it will either escape or unescape what I put into the textarea . This code works just fine , but my question has to do with how I am ch... | < a id='encode ' href='javascript : void ( 0 ) ' > encode < /a > | < a id='decode ' href='javascript : void ( 0 ) ' > decode < /a > | < br/ > < textarea id='randomString ' cols='100 ' rows= ' 5 ' > < /textarea > < script type='text/javascript ' > $ ( document.ready ( function ( ) { $ ( ' # encode ' ) .click ( function ... | Refer to immediate selector object with jQuery ? |
JS | We unfortunately do a lot of dynamic web page design by building strings of HTML using JavaScript and using document.write to output the data . I stumbled upon some code that one of my coworkers wrote that looks like the following : These lines go on and on , sometimes hundreds of lines of hard-coded HTML ( with inline... | var myString = String ( ) + `` this is my string '' + `` and I am doing a lot of string concatenation '' + `` doing this the worst way possible '' | String Concatenation with String ( ) |
JS | I was trying some things today and came across a behaviour I would like to understand.But if it is defined like thisShouldn ’ t this be an error ? Did zero somehow become an object here ? Is it somehow equivalent to the following ? My question is not how regular destrcuturing and default params work , but only how this... | var b = ( { a = 1 , b = 1 , c = 1 } ) = > a + b + c ; b ( ) ; // throws error . var b = ( { a = 1 , b = 1 , c = 1 } = 0 ) = > a + b + c ; b ( ) // returns 3b ( [ ] ) // returns 3 var b = ( { a = 1 , b = 1 , c = 1 } = { } ) = > a + b + c ; // this is possible I guess . | How does this particular scenario of default params and destructuring work ? |
JS | Taken an example ifHere Func has property called prototype and I can add my custom methods like the following.As per my understanding here prototype is just another property of Func which is by default provided by the interpreter and is not used to delegate any functionality , ie . there is nothing likeApplying the sam... | var Func = function ( ) { } Func.prototype.move = function ( ) { //do something } Func.move ( ) Func.method = function ( ) { //do something } var obj = new Func ( ) ; | Understanding prototype Property of function |
JS | I am trying to create a regex that validates the 2 first characters of an international phone number as the user types it in : Is valid : + , 0 , + followed by a number , 00 , 0032476382763 , +324763Is not valid : 0 followed by a number different than 0 , ++ , everything that is not in the valid listSo far I have come ... | / [ 0 ] | [ 00 ] | [ + ] | [ +\d ] ] /g | Regex to check beginning of international phone number |
JS | In this example : And in this other : Do those conditions return the first part , the second or both ? | for ( var c = 0 , e = a.length ; c < e & & ! ( d = b ( c , a [ c ] ) , ! 1 === d ) if ( d = b ( c , a [ c ] ) , ! 1 === d ) | In JavaScript what is a ' , ' in a conditional |
JS | Given this code from Twitter 's new hogan.js library to demonstrate the issue ; what is the goal of naming the function twice ? | render : function render ( context , partials ) { return this.r ( context , partials ) ; } , | Named Object Property Functions |
JS | I 'm using Foundation 5 to set up a basic page . I 'm trying to get a button to change the background-image of a certain div . So far this works , but it only displays a certain area of the image.This is the code I have so far : The goal I want to achieve : I want to have the image on a full size within the certain div... | function cW ( ) { document.getElementById ( `` panel '' ) .style.backgroundImage = `` url ( 'https : //dl.dropboxusercontent.com/u/36821301/csgo % 20backgrounds/crimson-web.jpg ' ) '' ; document.getElementById ( `` panel '' ) .backgroundImage.style.maxWidth = `` 100 % '' ; } < ! DOCTYPE html > < html lang= '' en '' > <... | Foundation 5 : Styling my img size to the be 100 % of a div |
JS | I have this code below : It alerts two times : Why is the return value 'undefined ' ? It must be 1 . Where am I missing ? | alert ( 'Returned value : ' + myid_templates_editor_image_id_generator ( ) ) ; //Generates unique id for every image createdfunction myid_templates_editor_image_id_generator ( ) { ( function ( $ ) { var a = 1 ; while ( true ) { if ( $ ( ' # myid_templates_editor_image_ ' + a ) .length == 0 ) { alert ( 'Inside value : '... | Function returns 'undefined ' value |
JS | I was creating a new Date object like so : Sun Apr 01 1951 01:00:00 GMT+0300and as you can see , I wanted the hours to be ' 0 ' and instead got ' 1'.I know the Date object is being affected by timezone , but if I do this : Mon Apr 02 1951 00:00:00 GMT+0300the timezone remains the same but now the hours portion of the d... | new Date ( 1951 , 3 , 1 , 0 , 0 , 0 , 0 ) ; a = new Date ( 1951 , 3 , 2 , 0 , 0 , 0 , 0 ) | Javascript Date c ` tor returns wrong hours |
JS | I 'm trying to select an object with JQuery filtering by a value of an attribute that is a unique filename . I ca n't escape from slashes when the selector is made with a var . I lost 2 hours trying with multiple combinations but I think I 'm missing something . Thanks in advance for the lightMy HTML : My Javascript : ... | < table class= '' table table-condensed '' id= '' CLKPMTable_2 '' > < tbody > < tr class= '' click-row '' valuetype= '' PM '' filename= '' \\server\folder\file1 '' paymentmethodid= '' 1 '' > < td class= '' col-md-1 '' > < img width= '' 24 '' height= '' 24 '' src= '' /Content/img/123.png '' id= '' PMURLIMG_ '' > < /td >... | Jquery Select an attribute with slashs |
JS | What I am trying to achieve is to get the combination of alphabets from a given input number . For eg . if I give an input of 111 , the output should be [ 'AAA ' , 'KA ' , 'AK ' ] . If the input is 1111 , the output should be [ 'AAAA ' , 'KAA ' , 'AKA ' , 'AAK ' , 'KK ' ] . The partial working code is as follows where ... | < html > < head > < h1 > Javascript < /h1 > < /head > < body > < script > var dataset = { A : ' 1 ' , B : ' 2 ' , C : ' 3 ' , D : ' 4 ' , E : ' 5 ' , F : ' 6 ' , G : ' 7 ' , H : ' 8 ' , I : ' 9 ' , J : '10 ' , K : '11 ' , L : '12 ' , M : '13 ' , N : '14 ' , O : '15 ' , P : '16 ' , Q : '17 ' , R : '18 ' , S : '19 ' , T ... | Displaying all possible combinations of alphabets from a dataset for a given input number |
JS | So i have created a form . Upon submitting that form , i created a confirmation tab so that the user can confirm his inputs . once the user confirms the inputs , the form will be submitted.So i have added jquery to display the confirmation tab however , when i click the button to show the confirmation tab , the form ju... | < div class= '' tab-content '' > < fieldset class= '' tab-pane active '' id= '' form_tab '' > < form id= '' poform '' method= '' GET '' > < table > < tr > < th colspan= '' 2 '' > < div class= '' header_3 '' > Pre-Order Form < /div > < /th > < /tr > < tr > < td > < label > Account Number : < /label > < /td > < td > < in... | confirmation tab does not show up |
JS | Given an array of strings : and another array of strings : How can I return true if all the strings from first_array are present in the second_array and false otherwise ? | const first_array = [ 'aaa ' , 'bbb ' , 'ccc ' ] const second_array = [ 'aaa ' , 'bbb ' , 'ccc ' , 'ddd ' , 'eee ' ] | Find all strings from an array in another array |
JS | ` I 'm reading 'JavaScript : the definitive guide ' and I 'm getting hung up on an example : “ you can use code like the following to copy the names of all object properties into an array '' I do n't understand , why does the last line really do anything , without instructions . Why does it fill the array ? | var o = { x:1 , y:2 , z:3 } ; var a = [ ] , i = 0 ; for ( a [ i++ ] in o ) /* empty */ ; | Copying object properties to array with an empty body for-in loop |
JS | So I 'm getting into Reactjs with very basic component.I 'm logging out the same state from different functions , but what I 'm seeing is the different values.Output after some clicks and wait , log is : I expect the `` count '' to be the same in both functions.Can any one explain this ? Thank so much . | import React , { useState , useEffect , useRef } from `` react '' ; const Test = props = > { const [ count , setCount ] = useState ( 0 ) ; useEffect ( ( ) = > { setInterval ( ( ) = > { console.log ( `` count in interval is : '' , count ) ; } , 1000 ) ; } , [ props ] ) ; function btnClick ( ) { const newCount = count + ... | ReactJS : Why different values from one state ? |
JS | I have these two arrays : main : filtered : I need to get the items of main which have as id those contained in filtered with the property : link_id , I tried with : the problem is that this will return null , and also this does n't allow me to check if link_id is null | [ { id : `` 1 '' } , { id : `` 2 '' } , { id : `` 3 '' } ] [ { id : `` 80 '' , link_id : `` 1 '' } , { id : `` 50 '' , link_id : null } , { id : `` 67 '' , link_id : `` 3 '' } ] main.filter ( x = > filtered.includes ( x.id ) ) ; var main = [ { id : `` 1 '' } , { id : `` 2 '' } , { id : `` 3 '' } ] , filtered = [ { id :... | How to get difference between two array of object with different property comparer ? |
JS | Here 's a very basic example to demonstrate what I mean : ( And the TypeScript playground link for an editable example . ) Why does action ( payload ) not throw an error when the type of payload that 's passed in ( GreatPayload ) is clearly a mismatch for the function argument type Payload ? | type Payload = { id : number ; } type GreatPayload = { id : number ; surprise : 4 ; } type Action = ( payload : Payload ) = > void ; const action : Action = payload = > null ; const payload : GreatPayload = { id : 1 , surprise : 4 , } ; action ( { id : 1 , surprise : 4 } ) ; // < == as expected , this errors out becaus... | Why does TypeScript not throw an error when the function argument type is mismatched ? |
JS | The usual way of adding Javascript to a page is by adding it to the document 's < body > or < head > in either static HTML or something generated server-side.I would like to generate dynamic Javascript , and add it to the document in a dynamic fashion ; that is on-demand and during run-time . For example Javascript cod... | var scriptContent = 'console.log ( `` dynamic script '' ) ; ' ; var s = document.createElement ( 'script ' ) ; s.text = scriptContent ; document.body.appendChild ( s ) ; < domainname > :1:1separate_js_file.js:14:20 | Injecting Javascript code from string pretending to be an external script |
JS | I have to create a navigation path for ships . All the ships come to a center point and halt there for a while.The coordinates of the ships and the center point ( MotherShip ) come from the database.The code to select the data . The center point is static.The problem is that there are some ships that start from the cen... | < ? php $ sqlqry = `` SELECT * FROM ship WHERE id= '' . $ id . `` AND start_date BETWEEN ' '' . $ s_date . `` ' AND ' '' . $ e_date . `` ' '' ; $ result = mysqli_query ( $ bd , $ sqlqry ) ; $ locations = array ( ) ; $ counter=0 ; while ( $ row = mysqli_fetch_array ( $ result ) ) { array_push ( $ locations , $ row ) ; }... | Create a proper path for navigation |
JS | I 'd like to implement an autoprefixer pre-processor for the Punch static site generator . However , in Punch parlance , I 'm not sure if this would qualify as a compiler , minifier , etc . I 've tried all of the above to no avail.Here 's my most recent attempt at getting anything working : ./autoprefixer.jsconfig.json... | module.exports = { input_extensions : [ `` .css '' ] , force_compile : true , compile : function ( input , filename , callback ) { return callback ( null , `` * { color : red ; } '' ) ; } } ; ... `` plugins '' : { `` compilers '' : { `` .css '' : `` punch-sass-compiler '' , `` .css '' : `` autoprefixer '' } } ... /home... | How do I implement a Punch Autoprefixer Pre-Processor ? |
JS | In the following code , orange 's constructor logs as its parent 's constructor ( Plant ( ) ) as opposed to Fruit ( ) which is its . Why is this so ? ( Sorry about the random objects . It 's the middle of the night and I 'm just learning some JavaScript . Did n't think too much about them to make sense in the real worl... | function Plant ( name , colour ) { this.name = name ; this.colour = colour ; } Plant.prototype.print = function ( ) { return `` I 'm a `` + this.name.toLowerCase ( ) + `` and I 'm `` + this.colour.toLowerCase ( ) + `` . `` ; } var mango = new Plant ( `` Mango '' , `` Orange '' ) ; console.log ( mango.constructor ) ; fu... | Why does an object 's constructor correspond to the parent 's constructor ? |
JS | I have a javascript script that looks for the value and of dropdown and changes the next dropdown menu based on what the value is , however this will no longer work for me as i need to pass the value back to ruby so i can save it in sessions.Thank you for any help , I 'm fairly new to Javascript and am trying my best b... | $ ( document ) .ready ( function ( ) { $ ( ' # Exposures ' ) .bind ( 'change ' , function ( ) { var elements = $ ( 'div.exposures ' ) .children ( ) .hide ( ) ; // hide all the elements var value = $ ( this ) .val ( ) ; if ( value.length ) { // if something is selected elements.filter ( ' . ' + value ) .show ( ) ; // sh... | How to get my javascript to look for class or anything other than val |
JS | Is there any benefit to setting the array 's length before assigning values ? For example , or evenversus | let arr = [ ] ; arr.length = 10 ; arr [ 0 ] = ' a ' ; // arr.length === 10 ... arr [ 9 ] = ' i ' ; // arr.length === 10 let arr = new Array ( 10 ) ; arr [ 0 ] = ' a ' ; // arr.length === 10 ... arr [ 9 ] = ' i ' ; // arr.length === 10 let arr = [ ] ; arr [ 0 ] = ' a ' ; // arr.length === 1arr [ 1 ] = ' b ' ; // arr.len... | Is it more efficient to declare the length of array before assigning values at its indices ? |
JS | Can you add the javascript in the desired *.html files without including in each of the *.html files ? Like : So can I use a method that will automatically include my desired javascript file in my any future desired *.html files without manually adding < script > tags in my html files ? Just like htaccess that will red... | < html > < head > ... ... < ! -- no script -- > < /head > < body > ... ... < ! -- also no script tags -- > < /body > < /html > | HTML & Javascript - Including a javascript on all the websites in a domain |
JS | In strongly typed languages such as Java , there is no need to explicitly check the type of object returned since the code can not compile if the return types do not match method signature . Ex . You can not return a boolean when an integer is expected.In loosely typed languages such as Ruby , JavaScript , Python , etc... | module FirstModule TypeA = Struct.new ( : prop1 , : prop2 ) self.create_type_a TypeA.new ( 'prop1Val ' , 'prop2Val ' ) endend module TypeARepository def self.function_to_test FirstModule.create_type_a # This will return TypeA object endend RSpec.describe `` do describe `` do before do allow ( FirstModule ) .to receive ... | In unit testing loosely typed languages , should the return type of methods be checked ? |
JS | I have a leader board with two lists which toggle . When I press weekly scorecard - weekly list is displayed and when I press overall Scorecard , overall is displayed.Just for reference , it works a bit like this : https : //jsfiddle.net/pvwvdgLn/1/My list has 1000 employees.The problem is that the search box , which i... | < div class= '' tab-content '' > < div id= '' weeklylb '' class= '' leadboardcontent '' > < div class= '' leaderboard '' id= '' leaderboard '' > < ol id = `` myOL '' > < mark > < ? php $ sql11 = `` SELECT * FROM pointsBadgeTable WHERE WeekNumber ='week04 ' ORDER BY pointsRewarded desc '' ; if ( ( $ stmt1221 = sqlsrv_qu... | search for elements in a list |
JS | I have the following code in my service worker : However , it 's doing some weird stuff in the dev console and seems to be making the script load asynchronously instead of synchronously ( which in this context is bad ) .Is there any way to listen for when a request is completed without calling fetch ( event.request ) m... | self.addEventListener ( 'fetch ' , function ( event ) { var fetchPromise = fetch ( event.request ) ; fetchPromise.then ( function ( ) { // do something here } ) ; event.respondWith ( fetchPromise ) ; } ) ; // This does n't workself.addEventListener ( 'fetch ' , function ( event ) { event.request.then ( function ( ) { /... | Seeing if a request succeeds from within a service worker |
JS | I have 10 divs which were displayed in a random time.How can I set the last shown div on top ( rank first position ) each time and not in the html order of the divs ? Here is my code : Here is my fiddle : https : //jsfiddle.net/gkq21ppt/3/EDIT : Idea for a solutionA solution could be , to wrap the divs and set them col... | var myVar ; function showDiv ( ) { var random = Math.floor ( Math.random ( ) * $ ( '.notification ' ) .length ) ; $ ( '.notification ' ) .eq ( random ) .fadeIn ( 200 ) .delay ( 3000 ) .fadeOut ( 200 ) ; createRandomInterval ( ) ; } function createRandomInterval ( ) { setTimeout ( showDiv , 500+ Math.random ( ) * 4000 )... | Show last fadeIn div on first position |
JS | I have two drop menus that I need to close when a user clicks outside of them , or on the other drop menu . I have tried several methods without success and only one works slightly . Currently , the `` state '' menu will open and close properly ( the first time ) and then not work correctly the second time . but will w... | < div class= '' state_box '' > < input type= '' checkbox '' id= '' state-tgl '' onblur= '' myFunction ( ) '' > < label id= '' state-tgl-label '' for= '' state-tgl '' > < span class= '' collapse_tiny '' > Choose a state < /span > < img src= '' /images/template2014/dropdown-black.svg '' style= '' vertical-align : middle ... | Drop menu wo n't close properly |
JS | I 've encountered an odd situation . I 'm building a nice little Tic-Tac-Toe game in JS , and I ca n't figure out why the count variable will not reset when I init ( ) a second time . The first game works well ; the second game count does not reset to 0 even though the var count resets in init ( ) . Game rules : game s... | var board ; var gameBoard ; var winners = [ [ 0,1,2 ] , [ 3,4,5 ] , [ 6,7,8 ] , [ 0,3,6 ] , [ 1,4,7 ] , [ 2,5,8 ] , [ 0,4,8 ] , [ 2,4,6 ] ] ; var count ; var checkWin = function ( a ) { for ( var i = 0 ; i < winners.length ; i++ ) { if ( gameBoard [ winners [ i ] [ 0 ] ] === a & & gameBoard [ winners [ i ] [ 1 ] ] === ... | Count variable does not reset in javascript when re-initialized |
JS | How can I get the `` e '' elements inside of `` arr '' to be replaced by change0 ? The arr array will be an input by the user and I need to change it there is no way to predict which element will be `` e '' . | var arr = [ `` a '' , `` b '' , `` c '' , `` d '' , `` e '' , `` f '' , `` g '' , `` h '' , `` e '' , `` j '' , `` e '' ] ; var change0 = 2var change1 = 1document.write ( arr ) ; | How can I change elements inside and array |
JS | I have the following in index.html : And the following in program.js : Opening index.html for the first time , this is produced ( output A ) : Then , after refreshing the page , this is produced ( output B ) : I do not ever see output B in Firefox.Going back to Chrome : if , however , I use some variable other than 'na... | < html > < body > < pre > < script src= '' program.js '' > < /script > < /pre > < /body > < /html > document.writeln ( JSON.stringify ( name ) ) ; name = `` Bob '' ; > `` '' > `` Bob '' document.writeln ( JSON.stringify ( val ) ) ; val = `` Bob '' ; Uncaught ReferenceError : val is not defined | odd javascript remembrance in Chrome |
JS | is there a way to create a switch comparator like this one ? | switch ( item ) { case ( item < = 10 ) : money += 25 ; $ ( ' # money ' ) .html ( money ) ; break ; case ( item > 10 & & item < = 20 ) : money += 50 ; $ ( ' # money ' ) .html ( money ) ; break ; } | How to create a switch comparator in JS ? |
JS | I want to implement a jQuery scrollspy to one of the projects I am working on.I found this jsfiddle ( https : //jsfiddle.net/mekwall/up4nu/ ) which I managed to implement into my project . I wish to modify it but am stuck at trying to understand what this bit of code means.I know in general , the code will search for a... | var topMenu = $ ( `` # top-menu '' ) , menuItems = topMenu.find ( `` a '' ) , // Anchors corresponding to menu items scrollItems = menuItems.map ( function ( ) { var item = $ ( $ ( this ) .attr ( `` href '' ) ) ; if ( item.length ) { return item ; } } ) ; $ ( $ ( this ) .attr ( `` href '' ) ) ; $ ( this ) .attr ( `` hr... | What does the extra `` $ ( ) '' in `` $ ( $ ( ) ) '' selector do ? |
JS | ( see Update at the bottom for a live demo of what I want ) I have an online game with a chat system , but the CSS suck.Example with images : And two code exampleHere I have used absolute with the position of the user , and the speech can be going on others speech.And 'what I want ' demoHere I have what I want but with... | .speech-container { position : absolute ; top:0 ; left:0 ; height:250px ; background : rgba ( 0,0,0 , .15 ) ; width:100 % ; } .speech { background : white ; border:1px solid brown ; padding:10px ; border-radius:5px ; position : absolute ; } < div class= '' speech-container '' > < div class= '' speech red '' style= '' l... | Chat system align |
JS | i want to get the age of a particular name , lets say i want to get the age of Garrett Winters , using jquery . the record can be at any row of the table.i have to search the whole table and get the corresponding age in a variable..i want to search the column Name for a particular value and get the corresponding age i ... | < table id= '' table1 '' border= '' 1 '' cellspacing= '' 0 '' width= '' 100 % '' > < thead > < tr > < th > Name < /th > < th > Position < /th > < th > Office < /th > < th > Age < /th > < th > Start date < /th > < th > Status < /th > < /tr > < /thead > < tfoot > < tr > < th > Name < /th > < th > Position < /th > < th > ... | Get a cell value from a row based on another cell value |
JS | I am trying to check if an array of objects includes a object . I want it to return true when there is a object in the array that has the same values and the object id should not matter . This is how i thought it would work : But it returns false and I need it to return true . Do I have to convert every object in the a... | let arr = [ { r:0 , g:1 } ] ; let obj = { r:0 , g:1 } console.log ( arr.includes ( obj ) ) ; let arr = [ JSON.stringify ( { r : 0 , g : 1 } ) ] let obj = { r : 0 , g : 1 } console.log ( arr.includes ( JSON.stringify ( obj ) ) ) ; | Check if array of objects includes an object |
JS | I 'm new to JavaScript and trying to get my head around some of the fundamentals of OOP and simulated `` classes '' . Upon executing the final line of this script , I would like the invoked this object pointer on line 4 to refer to the farm object ( just like it correctly does in line 2 and 3 ) . Unfortunately it does ... | var Building = function ( cost ) { this.cost = cost ; this.printCost = function ( ) { document.getElementById ( this ) .innerHTML = this.cost ; } } var farm = new Building ( 50 ) ; farm.printCost ( ) ; < html > < body > < p id= '' farm '' > < /p > < /body > < /html > | Function changing the `` this '' variable |
JS | How to create an NPM package with definition files where declared only interfaces in *.ts files.Let 's suppose we have two interfaces and one class defination : I need to pack these *.ts files in package npm , how to do that ? Should I export them in index.ts ? My package.json is : My tsconfig.json is : Inside index.ts... | export interface A { id : number ; } export interface B { name : string ; } export class C { } { `` name '' : `` npm '' , `` version '' : `` 1.0.0 '' , `` description '' : `` '' , `` main '' : `` index.js '' , `` scripts '' : { `` test '' : `` echo \ '' Error : no test specified\ '' & & exit 1 '' } , `` author '' : `` ... | How to create npm package with definition files ? |
JS | What impact does eventlisteres have ? Im talking about big numbers , here 's an example : There 's only x amount of .marker at firstAll children are added via JS when .marker is clicked - eventlistenerEach child does it 's own thing which means each of them have their own eventlistenersPlease do n't mind other things ,... | < ! -- Final HTML of single .marker when it has been clicked -- > < div class= '' marker '' > < div class= '' remove '' > < /div > < div class= '' change '' > < /div > < div class= '' add '' > < /div > < div class= '' drag '' > < /div > < /div > var count = 20 000 ; for ( i = 0 ; i < count ; i++ ) { var marker = docume... | Eventlisteners impact ? |
JS | I am a beginner in HTML and php ( everything ) .I got 4 types of fields ( comment form ) : select one from a list ( option tags ) type text ( e.g . name ) type comment ( textarea ) checkbox ( tick all or one or none ) I have Javascript ( prevent name and email to be left empty ) : I have a language field and you select... | < script > function validateForm1 ( ) { var x = document.forms [ `` form_contact '' ] [ `` name '' ] .value ; if ( x == null || x == `` '' ) { alert ( `` Name must be filled out '' ) ; return false ; } var x = document.forms [ `` form_contact '' ] [ `` email '' ] .value ; if ( x == null || x == `` '' ) { alert ( `` Ema... | I got empty email from my comment form on my website |
JS | When having to format or transform some function parameters in JavaScript , I usually create homonymous private variables ( private variables with the same names as the function parameters ) : Question : is that considered bad practice ? Is there any drawback I should be concerned about ? | function myFunction ( param ) { var param = Math.floor ( param ) ; // More code referencing param many times here ... } | Homonymous function parameters and private variables |
JS | First div is a category and the second div contains some photos.I wanted to do something that when user clicks on an image the first div move 0.7 of the screen width to right and all images in second div disappear , so I wrote : When its full screen it works right , but when I resize the window and try again the first ... | $ ( document ) .ready ( function ( ) { $ ( `` img '' ) .click ( function ( ) { var my_width = screen.width * 0.7 ; $ ( `` .second_div '' ) .find ( `` img '' ) .hide ( ) ; $ ( `` .first_div '' ) .css ( { `` transform '' : `` translate ( `` + my_width + `` px,0px ) '' , `` -webkit-transform '' : `` translate ( `` + my_wi... | Divs are n't aware of screen resizing |
JS | PROBLEM : R Shiny – Make wellPanel pop-up follow as you scroll with CSSHi Stack Users , I 've created a Shiny application that has a data table wherein when a user clicks on a row , a hidden wellPanel will pop-up beside it to show more details related to that row.The length of the pop-up wellPanel is long but the lengt... | # # # # LOAD PACKAGES # # # # # # # # # # # # # # # # # # # # # # require ( shiny ) require ( shinyjs ) require ( data.table ) require ( dplyr ) require ( DT ) # # # # PREPARE DATA # # # # # # # # # # # # # # # # # # # # # # id < - c ( '10001 ' , '10002 ' , '10003 ' , '10004 ' , '10005 ' , '10006 ' , '10007 ' , '10008 ... | R Shiny – Make wellPanel pop-up follow as you scroll with CSS |
JS | I have a function in which I am first checking that a string passed as argument has letters only or not . But it always return as false . Below is my jsfiddleThe above code always alerts Only letters please . | function takeString ( str ) { var regex = `` /^ [ A-Za-z ] + $ / '' ; if ( str.match ( regex ) ) { if ( str.charCodeAt ( 0 ) === str.toUpperCase ( ) .charCodeAt ( 0 ) ) { alert ( 'true ' ) ; return true ; } else { alert ( 'false ' ) ; return false ; } } else { alert ( 'Only letters please . ' ) ; } } takeString ( 'stri... | Code does not pass first validation |
JS | I want to know if it 's possible to use the attr ( ) function inside a new plugin : I 've tried the code above but it does n't work . I 'm sure the memColor attribute exists because I 've tested it with an alert in the $ ( document ) .ready block . | ( function ( $ ) { $ .fn.resetColor = function ( ) { var oldColor=this.attr ( `` memColor '' ) ; this.css ( 'background-color ' , oldColor ) ; } ; } ) ( jQuery ) ; | Use the attr ( ) function inside a new plugin ? |
JS | I seem to be having a weird problem with the responsive CSS and the JQueryWhen the window is resized to 600pxThe hr ( icon ) is clicked to show NavOnce hr is clicked again to hide the nav , and the window is resized , the nav is n't visibleif nav is visible and then resized > 600px nav stays visible throughout.Is the p... | < div class= '' container '' > < div class= '' leftmenu '' > < div class= '' logo '' > < img src= '' http : //callmenick.com/theme/callmenick/img/logo.svg '' alt= '' '' / > < /div > < div class= '' icon '' > < hr/ > < hr/ > < hr/ > < /div > < div class= '' social '' > < span class= '' fa fa-facebook '' > < /span > < sp... | jquery div does n't show when toggle is closed |
JS | The Twitter widget library exposes a global variable twttr . I 'd like to modularize this library on the fly using webpack with exports-loader . The problem is that , while the twttr variable is immediately exposed , its properties are still undefined when accessing it synchronously.Live DemoSo , var twttr = require ( ... | console.log ( twttr.widgets ) ; // undefined setTimeout ( function ( ) { console.log ( twttr ) ; // now defined } ) ; | Why does this Twitter library delay the assignment of its object properties ? |
JS | This might look very obvious to some people , but I really could not figure out why something like this might be happening , so I 'm looking for any help possible ! I have expanding rows , and each row should expand to show its details when clicked on , or when next button is pressed . They show and hide properly when ... | var main = function ( ) { var curQuantity1 = 0 ; var curQuantity2 = 0 ; var curQuantity3 = 0 ; $ ( '.article ' ) .click ( function ( ) { $ ( '.description ' ) .hide ( ) ; $ ( '.article ' ) .removeClass ( 'current ' ) ; $ ( this ) .children ( '.description ' ) .show ( ) ; $ ( this ) .addClass ( 'current ' ) ; } ) ; $ ( ... | jQuery .hide ( ) only working half the time |
JS | The following expression seems to work as intended and return the current timestamp.However I ca n't understand why operators are applied in strict left-to-right order here.MDN says the member ( . ) operator has higher priority than new . This would mean that . must be applied before new . So the expression should be e... | new Date ( ) .getTime ( ) new ( Date ( ) .getTime ( ) ) ( new Date ( ) ) .getTime ( ) | Why are operators in the expression new Date ( ) .getTime ( ) applied in strict left-to-right order ? |
JS | I 'm in the process of converting some scripting from from ES6 to ES5 due to a dependency on the system executing the scripts . I 'm running into an issue with this particular command : I 'm not sure what they 're trying to accomplish with the '= > ( ) = > ' syntax and am unsure how to convert this to ES5 standard func... | transition.selectAll ( 'path.hidden-arc ' ) .attrTween ( 'd ' , d = > ( ) = > middleArcLine ( d ) ) ; | Converting = > ( ) = > to ES5 |
JS | I 'm working on a Nativescript-Vue app , and I 'm trying to use Vuex to store the hour and minute from a Timepicker to use in other Pages . I 've tried catching the event with a computed property , but is there a better way of doing this with Vue ? Here 's what I have : Then , in my Vuex store : It appears that the def... | // In NotifyTimePicker.vue ( a custom Time-picking modal ) // Template : < TimePicker row= '' 2 '' col= '' 0 '' colSpan= '' 3 '' horizontalAlignment= '' center '' : hour= '' selectedFromHour '' : minute= '' selectedFromMinute '' / > //Scriptcomputed : { selectedFromHour : { get : function ( ) { return this. $ store.sta... | Nativescript Vue Timepicker with Vuex |
JS | I 'm using jQuery UI slider and drag and drop to create a way of specifying a rating out of 100 for each div.The problem is when I drag my divs onto the slider , I do not know how to get the value for the position of each div on the slider . Here is a plnk + some code ; http : //plnkr.co/edit/wSS2gZnSeJrvoBNDK6L3 ? p=p... | $ ( init ) ; function init ( ) { var range = 100 ; var sliderDiv = $ ( ' # ratingBar ' ) ; sliderDiv.slider ( { min : 0 , max : range , slide : function ( event , ui ) { $ ( `` .slider-value '' ) .html ( ui.value ) ; } } ) ; var divs = '.itemContainer ' $ ( divs ) .draggable ( { containment : ' # content ' , cursor : '... | How to show value of Jquery slider into multiple dropped divs |
JS | ContextI 'm trying to implement a feature so that when the user clicks on a checkbox within a table , the attribute value and data-title of the checkbox should be stored in a JS object literal named selected as a new key-value pair array element . In case the user clicks a second time on the same checkbox , the corresp... | var selected = { items : [ ] } ; $ ( ' # table ' ) .on ( 'click ' , 'input [ type= '' checkbox '' ] ' , function ( ) { var found = false ; $ .each ( selected.items , function ( i , val ) { if ( val.key == $ ( this ) .attr ( `` value '' ) ) { selected.items.splice ( i ,1 ) ; found = true ; return false ; //step out of e... | Remove array from javascript object |
JS | I would like to be able to include the file with a given order while compiling my coffeescript files into js with coffeebar.I would like to have the files settings.coffee , constants.coffee included first Code Snippet For now the script is only compiling the whole thing together according to its own logic.I would appre... | -- | -- settings.coffee| -- constants.coffee| -- page1.coffee| -- page2.coffee fs = require 'fs ' { exec , spawn } = require 'child_process'util = require 'util'task 'watch ' , 'Coffee bar Combine and build ' , - > coffee = spawn 'coffeebar ' , [ '-w ' , '-o ' , './../js/main/kc.js ' , './ ' ] coffee.stdout.on 'data ' ... | How to give an Order to the files compiled with coffeebar |
JS | This is something that I 'm sure I should know the answer to , but either I 'm just being stupid or I 've just somehow never come across this before ... Given the following array , declared in the global scope : I would have expected this to refer to the Window object . However , when calling the function : It appears ... | var arr = [ function ( ) { console.dir ( this ) ; } ] ; arr [ 0 ] ( ) ; //Logs Array var func = arr [ 0 ] ; func ( ) ; //Logs Window | What is the context of a function in an array ? |
JS | How can i get variable in handler function of obj ? Without reference of the obj in MyClass . That 's construction need you , if you use Base.js or another similar way of oop._.bindAll ( obj ) ( underscore metod ) also not suitable . It 's break overriding in Base.js . | var obj = { func : function ( ) { var myClass = new MyClass ( ) ; myClass.handler = this.handler ; myClass.play ( ) ; } , handler : function ( ) { //Here i do n't have access to obj console.log ( this ) ; //MyClass console.log ( this.variable ) ; //undefined } , variable : true } ; function MyClass ( ) { this.play = fu... | How to call key of object inside of callback ? |
JS | This is a smaller version of the array i have but it has the same structurewith const arr below , i want to create 2 new arrays with unique values that are sorted in ascending orderwhat i have above works , but seems a bit messy and was wandering if there was a better/tidier way of doing this | const arr = [ { tags : [ ' f ' , ' b ' , 'd ' ] , weight : 7 , something : 'sdfsdf ' } , { tags : [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] , weight : 6 , something : 'frddd ' } , { tags : [ ' f ' , ' c ' , ' e ' , ' a ' ] , weight : 7 , something : 'ththh ' } , { tags : [ ' a ' , ' c ' , ' g ' , ' e ' ] , weight : 5 , ... | Filtering an array of objects that contain arrays |
JS | I 've noticed this interesting problem : As far as I know , x.constructor should be b , but it 's actually a when b inherits from a through its prototype ? Is there a way I can inherit from a without screwing up my constructor ? | function a ( ) { this.aprop = 1 ; } function b ( ) { this.bprop = 2 ; } b.prototype = new a ( ) ; // b inherits from avar x = new b ( ) ; // create new object with the b constructorassert ( x.constructor == b ) ; // falseassert ( x.constructor == a ) ; // true | keeping the constructor correctly after inheritance |
JS | consider the following : foo intends to take the arguments object and rearrange the order , moving arg1 to the position of arg2bar calls foo with it 's argumentsI expect the result of the following to be something like { 0 : 'hello ' , 1 : undefined , 2 : 'world ' } However , i get : I am at a complete loss as to why t... | function foo ( args ) { args [ 2 ] = args [ 1 ] ; args [ 1 ] = undefined ; } function bar ( a , b , c ) { foo ( arguments ) ; console.log ( arguments ) ; } bar ( 'hello ' , 'world ' ) ; { 0 : 'hello ' , 1 : undefined , 2 : 'world ' , 3 : undefined , 4 : undefined , 5 : undefined , 6 : undefined , 7 : undefined , 8 : un... | Why does the javascript arguments object behave so strangely when you try to modify it ? |
JS | I 've got a jQuery extension that I wrote for comparing 2 images . I call it on a `` control image '' using the following : The extension works exactly the way I intended . Inside the extension is a function called magnifyImage . I wanted to add a slider for someone viewing the tool that does n't have a scrollwheel on ... | currentCompare = jQuery ( ' # controlImage ' ) .imageZoomCompare ( { ... options ... . } ) < input type= '' range '' id= '' imageZoomLevel '' name= '' imageZoomLevel '' min= '' 2 '' max= '' 10 '' value= '' 2 '' onchange= '' javascript : switchZoom ( this.value ) '' / > | Calling jQuery Extension Functions Externally |
JS | I have two trivial questions regarding the code above : Why is window.foo undefined ? Are n't all global variables attached to the window object by default ? Why is foo ===2 inside of the closure ? I know that I 'm passing the original bar with the alias foo , which is 2 , but outside of the function scope foo is still... | var foo = ' 1 ' , bar = ' 2 ' ; console.log ( foo , bar , window.foo ) ; //1 , 2 , undefined ( function ( foo ) { console.log ( foo , bar ) ; //2 , 2 } ) ( bar ) ; | Function scopes and global variables |
JS | I have a view with a simple button opening a modal in an Ionic+Angular app . And a modal template appearing correctly after the button is clicked : As you can see the modal contains 3 buttons , each calling the same function but with different parameter . I have this controller containing the function : The problem is ... | < ion-modal-view > < ion-header-bar > < h1 class= '' title '' > Popular tags < /h1 > < div class= '' buttons '' > < button class= '' button button-clear button-stable '' ng-click= '' closePopularForm ( ) '' > Close < /button > < /div > < /ion-header-bar > < ion-content > < div class= '' list '' > < div class= '' item-d... | Parameters messed up after function call from Ionic modal |
JS | I need some help here my code to let the button on the first click margin-top the container div 30px and on the second click -30px but it is not working please help me with this code . | function myFunction ( ) { document.getElementById ( `` tt '' ) .style.marginTop = `` 50px '' ; document.getElementById ( `` tt '' ) .style.marginTop = `` 80px '' ; } < div class= '' switcher '' style= '' margin-top : 30px ; background-color : # 430000 ; width : 300px ; height : 300px ; '' id= '' tt '' > < button id= ''... | Two functions on button clicks |
JS | This is more a question about what 's going on in my code . It works , but I need a little bit enlightenment ... I 'm using jQuery to create an event listener on an text input element . The HTML would simply be as follows : I need to receive events whenever someone types something into that field , and to avoid being f... | < input type= '' text '' id= '' autocomplete '' size= '' 50 '' / > jQuery ( ' # autocomplete ' ) .keyup ( function ( e ) { e.preventDefault ( ) ; clearTimeout ( this.timer ) ; this.timer = setTimeout ( function ( ) { jQuery.getJSON ( [ URL goes here ] , function ( data ) { // processing of returned data goes here . } }... | JavaScript , jQuery and 'this ' : what 's going on here ? |
JS | I 'm having this issue that I ca n't figure out what is happening : I 'm using Angular and it 's routing mechanism.so I have a url : As you can see there is an onclick= '' location.reload ( ) ; this works on Chrome and IE9 . But on FF it 's doing the following : Click on linkThe url get 's updatedThe location.reload ( ... | < a href= '' # /videos/detail/ { { video.Id } } '' onclick= '' location.reload ( ) ; '' > < div class= '' card-image '' > < img ng-src= '' { { video.ThumbnailUrl ? video.ThumbnailUrl : 'img/images.png ' } } '' src= '' '' / > < /div > < /a > < a href= '' # '' class= '' prevent '' ng-click= '' redirectwithreload ( ' # / ... | Reloading the page on FF not changing page |
JS | I 'd like to create a console ( think chrome 's dev console ) , in JavaScript for a web application , that has a persistent scope . So you would be able to say , set a variable , and then access that variable later in the console . Is there an easy way to do this in JavaScript ? An example session : | var x = SomeCustomFunction ( ) > > `` the result '' x.slice ( 4 ) > > `` result '' | Is it possible to create a console in JavaScript that provides a persistent local scope ? |
JS | I do n't know if this has been asked before , because English is not my first language and I do n't know the keywords to search.So basically I have the following input element , I would like to split the name into 3 parts like [ `` person '' , `` 0 '' , `` email '' ] .I have tried using / ( \ [ [ ^ [ \ ] ] ] ) |\./ but... | < input type= '' email '' name= '' person [ 0 ] .email '' / > | Split person [ 0 ] .email into [ 'person ' , ' 0 ' , 'email ' ] |
JS | Excuse me for this simple problem - but I seem to miss something obvious.Any pointer would be a great help.I have a JSON like I am trying to add another object ( at start preferably ) - but just could n't get it to work.Getting the below error : Uncaught TypeError : whatever [ 0 ] .put is not a functionfiddle | var whatever = [ { `` key1 '' : { `` text '' : `` text1 '' , '' group '' : `` 1 '' } , '' key2 '' : { `` text '' : `` text2 '' , '' group '' : `` 2 '' } , '' key3 '' : { `` text '' : `` text3 '' , '' group '' : `` 3 '' } } ] ; var str = ' { `` text '' : '' text0 '' , '' group '' : '' 0 '' } ' ; var obj = JSON.parse ( s... | Not able to insert object into array of json object |
JS | I 'm fairly new to coding and enlisted for the daily coding problem mailing list and got this question : Given a list of numbers and a number k , return whether any two numbers from the list add up to k.My solution ( after some stackoverflow digging ) looks like this ; I 'm wondering why it works . To me it looks like ... | function problemOne_Solve ( ) { const k = 17 ; const values = [ 11 , 15 , 3 , 8 , 2 ] ; for ( i=0 ; i < values.length ; i++ ) { if ( values.find ( ( sum ) = > { return k-values [ i ] === sum } ) ) return true ; } return false ; } | DailyCodingProblem , find pair in array that matches a given value |
JS | I want to create an integer or number that contains all the digits from an array of digits or string . How can I achieve that ? for example : should become | digitArry = [ 9 ' , ' 8 ' , ' 7 ' , ' 4 ' , ' 5 ' , ' 6 ' ] ; integer = 987456 ; | How to create an integer or number from array of digits or string of digits in JavaScript |
JS | In strict mode : example.call ( 'test ' ) # prints 'string'Otherwise , example.call ( 'test ' ) # prints 'object'However , console.log ( example.call ( 'test ' ) ) prints test ( as you 'd expect ) Why does Function.call change typeof 'test ' === 'string ' bound to this inside example ? | var example = function ( ) { console.log ( typeof this ) ; return this ; } ; | Function.prototype.call alters typeof this , outside strict mode ; why ? |
JS | I have a sample paragraph text in p tag . If i select some text in the paragraph . I am changing its text color to green from black and wrapping it in span tag adding a class selected for it . But i am able to select the text that is already selected . I do n't want the selected text to be selected again.I have given s... | function getSelectedText ( ) { t = ( document.all ) ? document.selection.createRange ( ) .text : document.getSelection ( ) ; return t ; } $ ( 'body ' ) .mouseup ( function ( ) { var selection = getSelectedText ( ) ; var selection_text = selection.toString ( ) ; var span = document.createElement ( 'SPAN ' ) ; span.textC... | How to overcome multiple selection issue |
JS | I 'm making CRUD and if I want to send some data to my backend ( node.js ) then I receive an error : angular.js:10765 POST http : //localhost:1234/shop/removeProduct/574bf938b16158b40f9c87bc 400 ( Bad Request ) script : The solution is just simply pack this parameter ( productId ) in an object like this : But why I hav... | $ scope.removeProduct = function ( partnerId , productId ) { $ http.post ( `` /campaign/removeProduct/ '' + partnerId , productId ) ; } $ scope.removeProduct = function ( partnerId , productId ) { $ scope.productData = { productId : productId } ; $ http.post ( `` /campaign/removeProduct/ '' + partnerId , $ scope.produc... | Why I have to send params as an object in $ http angular ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.