JavaScript - Why Is The Callwhy Is The Slice Method Only A Method Of An Array Instance?
Why is the callwhy is the slice method only a method of an Array instance? The reason why I ask is because if you want to use it for the arguments property of function object, or a string, or an object, or a number instance, you are forced to use Array.prototype.slice.call(). And by doing that, you can pass in any type of object instance (Array, Number, String, Object) into it. So why not just default it as a method of all object instances built into the language?
In other words, instead of doing this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; console.log(typeof arguments);//Object console.log(arguments instanceof Array);//false var args1 = Array.prototype.slice.call(arguments); console.log(args1); var args2 = Array.prototype.slice.call(obj); console.log(args2); var args3 = Array.prototype.slice.call(num); console.log(args3); var args4 = Array.prototype.slice.call(string); console.log(args4); Core('dom','event','ajax'); Why not just be able to do this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; var args = arguments.slice(0); var args2 = obj.slice(0); var args3 = num.slice(0); var args4 = string.slice(0); //right now none of the above would work but it's more convenient than using the call alternative. } Core('dom','event','ajax'); Why did the designers of the javascript scripting language make this decision? Thanks for response. Similar TutorialsCode: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email, courseID, titleArray, pointsArray){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; this.title = titleArray; this.points = pointsArray; this.assign = this.points.slice(0,4); this.exams = this.points.slice(-2); this.assignments = function() { return task(this.title,this.points); } this.totalPoints = function() {return addExam(this.assign,this.exams); } this.finalGrade = calcGrade; } Student.prototype = { constructor : Student, toString : studentInfo }; //assign and exam doesn't seem to hold no values inside.. ??? function addExam(assign,exams){ var exams=this.exams; var high1=exams[0]; var high2=0; while(high2<exams.length){ high1=Math.max(high1,exams[high2]); high2++; } var sum = 0; for (var i=0; i < assign.length; i++){ sum += assign[i]; } return sum + high1; } var totalPoints = addExam(); function calcGrade(){ var grade; if (totalPoints >= 190){ return "A+"; }else if (totalPoints >= 180){ return "A"; }else if (totalPoints >= 175){ return "B+" }else if (totalPoints >= 170){ return "B"; }else if (totalPoints >= 165){ return "B-"; }else if (totalPoints >= 160){ return "C"; }else if (totalPoints >= 150){ return "D"; }else if (totalPoints < 150){ return "F"; } } function studentInfo(){ return "Student : " + this.lastName + "," + this.firstName + "<br>"+ "eMail : " + this.email + "<br>" + "Course ID : " + this.courseID + "<br>" + "--------------------------------" + "<br>" + this.assignments() + "--------------------------------" + "<br>" + "Total Points : " + this.totalPoints() + "<br>" + "Final Grade : " + this.finalGrade(); } function createStudents(){ var student1 = new Student("Jake", "Hennry", "jhennery@gmail.com","COIN-070B.01", ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"], [25, 25, 28, 20, 29, 40, 40] ); alert("Student : " + student1.lastName + "," + student1.firstName + "\n"+ "eMail : " + student1.email + "\n" + "Course ID : " + student1.courseID + "\n" + "---------------------------------------" + "\n" + student1.assignments() + "\n" + "---------------------------------------" + "\n" + "Total Points : " + student1.totalPoints() + "\n" + "Final Grade : " + student1.finalGrade()); } var titleArray = ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"]; var pointsArray = [30, 30, 28, 27, 29, 41, 45]; var student = new Student("Haripriyaa", "Ganesan", "haripriyaa@gmail.com","COIN-070B.01", titleArray, pointsArray ); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. I am trying to impliment Javascript code to replace the MS Tabular data control. How do I go about creating a Fields collection object that has a default method of Item(idx) ie. myrs.Fields.Item(4).name is the same as myrs.Fields(4).name Have the code check that the statement has at least one character. You can do this by using the trim method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be: Statement: Response: Say something, please. Could someone help me with this? I'm not sure how to make it check to see if the user input has 0 characters. Hi there I'm trying to figure out what the following syntax for split means in the following line of the code arrTest[0].split('/')[0] what does ('/')[0] means in split('/')[0]? please can anyone explain Write a public static method named starPrinter that will take an int as a parameter and print lines of stars as shown below. The header of the method will be public static void starPrinter(int n) . This is what it should look like: Please help! Sup gents. Im having problems with the link method. Its tied up to a button in the form. The link method sees the "global" variable and determines if its 1 or 0. If its 1 it gives a certain msg and if its 0 another one. Problem its always reading the variable as 0 and giving me the same message regardless of the fact that im typing the username and password correc Code: <html> <head> <script type ="text/JavaScript"> var counter = 0; var counter2 = 0; var arraynumb = 0; var arraynumb2 = 0; var global; var array = ['Mohamad', 'Karim', 'Anthony', 'Rami', 'Natalia', 'Sarah', 'Samer', 'Violette', 'Plume', 'Sharshabil']; var array2 = ["1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009"]; function pass(){ var searchKey = document.searchform.inputVal.value; for (var i = 0, len = array.length; i < len; i++){ if (array[i] == searchKey){ counter = 1; arraynumb = i; } } } function pass1(){ var searchKey2 = document.searchform.inputVal2.value; for (var i = 0, len = array2.length; i < len; i++){ if (array2[i] == searchKey2){ counter2 = 1; arraynumb2 = i; } } } function access(global) { if (counter == 1 && counter2 == 1 && arraynumb == arraynumb2) { window.alert("You may now access the website"); global = 1; } else window.alert("You may not access the website"); global = 0; } function link(global) { if (global == 1) { window.alert("you may proceed to the link"); } else window.alert("you are not signed in, please do so"); } </script> </head> <body> <form name = "searchform" action = ""> <p>Enter username<br/> <input name = "inputVal" type = "text" size = "30"/> <input name = "search2" type = "button" value = "Search" onclick = "pass()"/> </p> <p>Enter password<br/> <input name = "inputVal2" type = "password" size = "30"/> <input name = "search" type = "button" value = "Search" onclick = "pass1()"/> <input name = "Access site" type = "button" value = "Access" onclick = "access()"/> <input name = "link to" type = "button" value = "link" onclick = "link()"/> <br/> </p> <br/> <p></p> </form> </body> </html> When you use a form and submit it the URL bar changes to what the submitted values are. So can anyone explain how to use this?
So I'm new around here, and to web dev in general, but I've got a (hopefully) short question. I am trying to call a function (nextMonth()) every second from the time that the cycle method gets called, until it is called again. As of now I am trying to use setInterval, (and I previously tried with setTimeout and using a callback argument but maybe I wasn't doing that properly). The problem is that after running the cycle() method for 5 or 6 seconds, the entire browser freezes up and you have to kill it and restart it. Here is my code as of now: Code: function cycle() { if(CYCLEINT != null) //STOP THE CYCLE LOOP { window.clearInterval(CYCLEINT); CYCLEINT = null; document.getElementById("cycle").innerHTML = "Cycle Months"; } else //LOOP IS NOT RUNNING, INITIATE AND CONTINUE INTERVAL. { CYCLEINT = self.setInterval("nextMonth()", 1000); document.getElementById("cycle").innerHTML = "Pause"; } } function prevMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal > 1) { dVal--; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } } function nextMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal < dateMax) { dVal++; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } if(CYCLEINT != null && dVal >= dateMax) { cycle(); } } Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm Code: window.onload = initForm; function initForm() { document.getElementById("months").selectedIndex = 0; document.getElementById("months").onchange = populateDays; } function populateDays() { var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31); var monthStr = this.options[this.selectedIndex].value; if (monthStr != "") { var theMonth = parseInt(monthStr); document.getElementById("days").options.length = 0; for(var i=0; i<monthDays[theMonth]; i++) { document.getElementById("days").options[i] = new Option(i+1); } } } Thank you! I am very interested in learning this and would love any help! I'm trying to write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0(1) up to that maximum power, inclusive. For example, I'm trying: printPowersOfN(4, 3); printPowersOfN(5, 6); printPowersOfN(-2, 8); which should give me: 1 4 16 64 1 5 25 125 625 3125 15625 1 -2 4 -8 16 32 64 -128 256 but I only get: 64 15625 256 Here's my code: Code: public class Powers { public static int printPowersOfN (int base, int exponent) { int answer = 1; for (int i=1; i <= exponent; i++) { answer*=base; } return answer; } public static void main(String[] args) { System.out.println(printPowersOfN(4, 3)); System.out.println(printPowersOfN(5, 6)); System.out.println(printPowersOfN(-2, 8)); } } What should I change so that it does all of the powers? I am using javascript for adding and removing rows from table as per user require ment like if we press ADDROW button it adds extra row to table and if we pressREMOVEROW it delets the last row.. Now i want to access the data from textbox like this.. var crpt = document.getElementById("itrtr2").value; //no. of rows for(var k=1;k<=crpt;k++) { qtyc = document.getElementById("txtRowc3"+k).value; unit_pricec = document.getElementById("txtRowc5"+k).value; alert('QTYC:'+qtyc+' UPC:'+unit_pricec); cttl = qtyc * unit_pricec; document.getElementById("txtRowc6"+k).value = cttl.toFixed(2); csbttl = csbttl + cttl; } document.getElementById("subttlC").value=csbttl.toFixed(2); it shows the value of textRowc3i in qtyc in alert box but also givs error document.getElementById("txtRowc3"+k) is null.. I tried for this but problem is not solved please help... Thank You... i want to write a code which would prompt the user for his first name and last name with space in between them.The full name must be entered in the same prompt box.Using the charCodeAt() method i wanna test the first character of the user's first name as well as last name.If the first character of first name is in lowercase then it should alert the user as "first name must start with uppercase".And if the first character of second name is in uppercase then it should alert the user as "second name must start with lowercase". ..plzzzz help me and give me some code for this..i m a beginner in javascript..
would it be better to place the javascript into a .js file or just place the js code somewhere else in the html? How should it look? Code: <div style="width: 225px; height: 155px; float: left; height: 16px; background-color: #000000; color: #FFFFFF; margin-left: 0px; margin-bottom: 0px; font-size: small; padding-left: 0px;"> <img alt="" src="images/news.png" height="16" width="222" /><div style="width: 225px; height: 155px; float: left;"><script type="text/javascript">// <![CDATA[if(document.layers){document.write('<ilayer id="ns4div" width="'+swidth+'" height="'+sheight+'" bgcolor='+sbcolor+'><div id="ns4div1" width="'+swidth+'" height="'+sheight+'" onmouseover="sspeed=0;" onmouseout="sspeed=rspeed"></div></ilayer>')} if(document.getElementById||document.all){document.write('<div style="position:relative;overflow:hidden;width:'+swidth+'px;height:'+sheight+'px;clip:rect(0 '+swidth+'px '+sheight+'px 0);background-color:'+sbcolor+';" onmouseover="sspeed=0" onmouseout="sspeed=rspeed"><div id="iens6div" style="position:relative;width:'+swidth+'px;"></div></div>');} // ]]></script> </div></div> Hello everyone, I'm working with the insertBefore method and am having a slight issue that l'm sure is very easy to fix but l can't figure it out. If you look at the following page and click the "add game" button you'll see that extra "game" tables are added to the page. http://www1.theworldlink.com/test/insertBefore.php In the above example the <div id="box_scores"></div> tag is found directly before the closing <body> tag (and l need it inside of a form element). however on this example: http://www1.theworldlink.com/test/insertBefore2.php I have the <div id="box_scores"></div> div inside of a form element as apposed to directly before the closing <body> tag and the script fails to work. Here is the JS code that l'm using: Code: newDiv = document.createElement("div"); newDiv.innerHTML = 'test test test'; my_div = document.getElementById("box_scores"); document.body.insertBefore(newDiv, my_div); and l'm certain the problem is he document.body.insertBefore(newDiv, my_div); I've tried: document.body.forms[0].insertBefore(newDiv, my_div); and several other varients but l can't figure it out.... any help would be greatly appreciated!!!! If anyone could help me, I would soooo appreciate it. I'm writing this program and I can't seem to figure out what the problems is. I'm new to this and really bad at it. public class Points { int ycoordinate; int xcoordinate; public Points(){ ycoordinate=0; xcoordinate=0; } public Points(int xcoord, int ycoord) { xcoordinate=xcoord; ycoordinate=ycoord; } public int getxcoordinate() { return xcoordinate; } public int getycoordinate() { return ycoordinate; } public void setxcoordinate(int xcoord) { xcoord=xcoordinate; } public void setycoordinate(int ycoord) { ycoord=ycoordinate; } public int distanceFromOrigin() { int point1=(xcoord-0)*(xcoord-0); int point2=(ycoord-0)*(ycoord-0); int distance=Math.sqrt(point1+point2); } public String Points() { String str="The distance between the coordinates is:"+""+distance; return str; } } Hello, I was able to solve an issue I had in previous post in writing some code to grab a section of a cookie value string (2 letter state ex MD) and check against it to do something. That was easy because the state was at the end of the string and all I had to do was use the slice() method. Now I was to be able to grab the 2 letter state from a string that looks like this: BALTIMORE, MD|blah blah|blah blah|blah blah (the real cookie value string will always be separated with pipes (|)) Can anyone please help? Thanks in advance! Code: <HTML> <HEAD> <TITLE></TITLE> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <SCRIPT LANUAGE="JavaScript"> function setCookie(name, value, expires, path, domain, secure) { document.cookie= name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); } </SCRIPT> </HEAD> <BODY> <script> $(function(){ $('div').each(function(){ if($(this).hasClass('stateSelect1')){ if (getCookie("location")!=null){ var state = getCookie("location").slice(-2).toLowerCase(); var stateArray = []; stateArray = $(this).attr('rel').toLowerCase().split(','); if($.inArray(state,stateArray) >= 0){ $(document).ready(function(){ $(".stateSelect0").css("display","none"); $(".stateSelect1").css("display","block"); }); } } } }); }); </script> <strong>Step 1. Copy and paste in cookie set text field:</strong> <br> <br> <strong>Show Image1:</strong><br> CHARLOTTE, NC|blah blah|blah blah|blah blah|blah blah<br> BALTIMORE, MD|blah blah|blah blah|blah blah<br> <br> <strong>Show Image2:</strong><br> COLUMBIA, SC|blah blah|blah blah|blah blah<br> RESTON, VA|blah blah|blah blah|blah blah<br> <br> <strong>Show Image3:</strong><br> LOS ANGELES, CA|blah blah|blah blah|blah blah<br> SEATLE, WA|blah blah|blah blah|blah blah<br> <br> <br> <strong>Step 2.</strong> <input type="button" value="Set Cookie" onclick='setCookie("location", prompt("Enter your location"))' /> <br> <br> <strong>Step 3.</strong> Now refresh page. <br> <br> <style> .default{ border:3px solid limegreen; margin-bottom:5px; width:200px} .div1{ border:3px solid red; margin-bottom:5px; width:200px} .div2 { border:3px solid purple; margin-bottom:5px; width:200px} .div3 { border:3px solid yellow; margin-bottom:5px; width:200px} .div4 { border:3px solid blue; margin-bottom:5px; width:200px} </style> <!--DEFAULT IMAGE IF NO COOKIE SET OR NON LISTED STATE--> <div class="stateSelect0 default"> DEFAULT IMAGE </div> <!--DEFAULT IMAGE IF NO COOKIE SET OR NON LISTED STATE--> <div class="stateSelect1 div1" rel="NC,MD" style="display:none">Image 1 - DIV 1</div> <div class="stateSelect2 div2" rel="SC,VA" style="display:none">Image 2 - DIV 2</div> <div class="stateSelect3 div3" rel="WA,CA" style="display:none">Image 3 - DIV 3</div> </BODY> </HTML> I could not figure out the answer, and could not find the answer from Google. I have following object PHP Code: ; var obj = function() { ; this.method_1 = function() { ; return this.method_2 } ; this.method_2 = function() { ; return 'my parameter' } } It works. If I want method_2 having parameter, I write it this way: PHP Code: ; var obj = function() { ; this.method_1 = function() { ; return this.method_2 } ; this.method_2 = function(para) { ; return para } } ; var newObj = new obj() ; window.alert(newObj.method_2('my parameter')) It works and returns "my parameter". If I want method_2's parameter to be assigned by method_1, I write it this way: PHP Code: ; var obj = function() { ; this.method_1 = function() { ; return this.method_2('my parameter') } ; this.method_2 = function(para) { ; return para } } It does not work. So, the question is how to assign a parameter of a method by another method? Thanks a lot. I cannot figure out how to return the array back to the main method! what am I doing wrong?? import java.util.*; //lab 3 public class Prices { public static void main(String[] args) { double []array; array = new double[10]; double fullPrice; fullPrice = fillPrices(array); System.out.println("testing"); } public static double fillPrices(double []tenValues) { Scanner input = new Scanner(System.in); double prices; System.out.println("Please enter 10 prices: "); for (int i = 0; i < 10; i++) tenValues[i] = input.nextDouble(); return tenValues; } } I thought you return an array by simply return (array name); Am i missing something? Thanks a bunch for whoever takes the time to help me! |